异常简单总结

异常捕获和抛出

处理异常中关键字有try、catch、finally、throw、throws

public class testException {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        System.out.println(a / b);
    }
}

​ 当运行上述代码块时,编译器会报错ArithmeticException。

当添加了异常捕获的代码后

public class testException {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try{
            System.out.println(a / b);
        }catch (ArithmeticException e){
            System.out.println("代码报错,不能除以0");
        }finally {
            System.out.println("最终表示");
        }
    }
}
//运行结果⬇
//代码报错,不能除以0
//最终表示

        try{
            //在这里加入可能会出错的代码块
        }catch (//这里用于添加要捕获的异常类型){
            //捕获异常后执行的代码
        }finally {
            //无论是否捕捉到异常都运行的代码
        }

1.可以使用多个catch捕获多种异常,但下面的catch所捕获的异常类型包含的内容不能大于上面catch所包含的异常类型

2.finally无论是否捕捉到异常也会执行代码,通常用于结束一些占用的资源,如IO

主动抛出异常 throw、throws

public class testException {
    public static void main(String[] args) {
        new testException().niceTry(1, 0);//匿名内部类调用方法
    }

    public void niceTry(int a, int b) {
	//在该方法中没有对a,b进行操作,虽然逻辑上有错误,但是正常运行是不会报错的。
        if (b == 0) {
            throw new ArithmeticException();//满足逻辑错误的条件后主动抛出异常
        }
    }
}//运行结果是编译器报错 ArithmeticException

主动抛出异常在方法内使用

public class testException throws ArithmeticException{}

throws在类上抛出异常

自定义异常

自定义异常只需要自定义一个异常类继承Exception

posted @ 2021-09-22 09:59  南晨晨晨  阅读(49)  评论(0)    收藏  举报