javaSE21/9/10

异常机制

分类

  • 检查性异常
  • 运行时异常
  • 错误

异常体系结构

  • Throwable是所有异常的超类
  • 在Java API中已经定义了许多异常类,这些异常类分为两大类,错误Error和Exception

Error

  • Error类对象由java虚拟机生成并抛出,大多数错误与代码编写想者所执行的操作无关
  • Error通常是灾难性的致命的错误,是程序无法控制和处理的

Exception

  • 重要的子类RuntimeException(运行时异常),其他为非运行时异常
  • Exception通常是可以被程序处理的
  • Ctrl + Alt + T捕获异常快捷键

捕获异常

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {//try可以监控区域
            System.out.println(a/b);
            //catch中的参数是想要捕获的异常
        }catch (ArithmeticException e){//如果try中的代码有异常,就会执行catch中的语句
            System.out.println("程序出现异常,b不能为0");
        }finally {//无论有没有异常,都会执行,处理善后工作,可以没有finally
            System.out.println("finally");
        }

    }
}

抛出异常

public class Test {
    public static void main(String[] args) {
        Test test = new Test();
        test.divition(1,0);
    }
    //假设这个方法中,处理不了这个异常,方法上抛出异常
    public void divition(int a,int b) {
        if(b==0){
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}

自定义异常

需要继承Exception

posted @ 2021-09-10 20:42  想吃坚果  阅读(37)  评论(0)    收藏  举报