美文网首页
二十五:Java基础入门-Java异常处理

二十五:Java基础入门-Java异常处理

作者: Lord丶轩莫言弃 | 来源:发表于2019-07-16 11:49 被阅读0次

    1、概述

    • 异常是导致程序中断运行的一种指令流,如果不对异常进行正确的处理,则可能导致程序的中断执行,造成不必要的损失。
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int temp = a / b;
        System.out.println(temp); // 会发生算术异常 
    }
    
    上述代码运行结果异常示意图.png

    2、处理异常

    1、异常格式
        try{
            异常语句
        }catch(Exception e){
        
        }finally{
            一定会执行的代码
        }
    
    // 异常捕获代码示例
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        int temp = 0;
        try {
            temp = a / b;
        } catch (ArithmeticException e) {
            System.out.println(e);
        }
        System.out.println(temp);
    }
    

    3、常见异常

    • 数组越界异常:ArrayIndexOutOfBoundsException
    • 数字格式化异常:NumberFormatException
    • 算术异常:ArithmeticException
    • 空指针异常:NullPointerException

    4、throws关键字

    • 在定义一个方法的时候可以使用throws关键字声明,使用throws声明的方法表示此方法不处理异常,抛给方法的调用者处理。
    public static void main(String[] args) throws Exception{
        tell(10, 0);
    }
    
    public static void tell(int i, int j) throws ArithmeticException {
        int temp = 0;
        temp = i / j;
        System.out.println(temp);
    }
    

    注意:当调用者将异常再往上抛的时候,异常由JVM处理。

    5、throw关键字

    • throw关键字抛出一个异常,抛出的时候直接抛出异常类的实例化对象即可。
    public static void main(String[] args) {
        try {
            throw new Exception("实例化异常对象");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    

    6、自定义异常

    • 自定义异常直接继承Exception就可以完成自定义异常类。
    class MyException extends Exception {
        public MyException(String msg) {
            super(msg);
        }
    }
    
    public class ExceptionDemo {
    
        public static void main(String[] args) {
            try {
                throw new MyException("自定义异常");
            } catch (MyException e) {
                System.out.println(e);
            }
        }
    
    }
    

    说明:该内容由Lord丶轩莫言弃收集整理,参考资料来源于极客学院

    相关文章

      网友评论

          本文标题:二十五:Java基础入门-Java异常处理

          本文链接:https://www.haomeiwen.com/subject/gymzkctx.html