Java之Exception

1,类体系

通过查看源码和api得知,其中异常,错误的类继承关系图如下

 

其中,顶层接口有两个子接口,Error和Exception,如果代码中少了分号或括号,那么运行程序会出错,而异常又分为编译时异常和运行时异常,编译时异常必须处理,不处理无法通过编译,运行时异常经常遇见,空指针异常(NullPointerException),类型转换异常(ClassCastException),数组越界异常(ArrayIndexOutOfBoundsException)等等,

 2,异常的处理

为了能让程序出现错误依旧可以继续执行下去,因此必须对异常经行处理

1)JVM默认处理异常的方式

运行下面代码

public class ExceptionDemo {
    public static void main(String[] args) {
        System.out.println("stat");
        int a = 100;
        int b = 0;
        System.out.println(a/b);
        System.out.println("over");
    }
}

会在控制台打印

 可见,JVM默认处理方式为 

1,在控制台打印一段数据,

2,调用System.exit(0)停掉当前程序

2)处理方式

那么我们自己该如何处理异常了

1,try catch 

try {
                //catch的参数为异常类型
        } catch (Exception e) {

        } finally {

        }

其中fanally会在最后执行,即使程序停止也会执行

执行流程如下

public static void main(String[] args) {
        int a =10;
        int b = 0;
        try {
            System.out.println(a/b);
        } catch (ArithmeticException ae){
            System.out.println("出现异常了");
        }
    }

1,当执行到 a/b 时,系统会抛出ArithmeticException 异常,

2,程序将catch中的异常和抛出的异常相杜比,如果一致,继续执行,如果不一致,交给JVM处理打印出

2,throws抛出异常

public float getResult(int a,int b) throws ArithmeticException{
        return a/b;
    }

3,自定义异常

一般继承Exception或者Runnable类,集体代码如下(来自菜鸟教程)

class WrongInputException extends Exception {  // 自定义的类
    WrongInputException(String s) {
        super(s);
    }
}
class Input {
    void method() throws WrongInputException {
        throw new WrongInputException("Wrong input"); // 抛出自定义的类
    }
}
class TestInput {
    public static void main(String[] args){
        try {
            new Input().method();
        }
        catch(WrongInputException wie) {
            System.out.println(wie.getMessage());
        }
    } 
}

控制台输入  

"Wrong input"
posted @ 2020-04-26 23:14  hunt1man  阅读(149)  评论(0编辑  收藏  举报