Java异常机制和 JavaSE 总结

发布时间 2023-11-01 11:40:20作者: 两块五的菜鸟

Java异常机制和 JavaSE 总结

1.什么是异常

​ 1.1检查性异常 用户错误

​ 1.2运行时异常 代码运行的异常

​ 1.3ERROR 不时代码的问题,可能时内存问题

2.Throwable 异常的超类(error || exception)

![](https://img2023.cnblogs.com/blog/808616/202311/808616-20231101113744885-1242989885.png)

​ PS: error 一般时JVM 报出的异常;exception 一般是运行异常

3.捕获和抛出异常

​ 关键字:try、catch、finally、throw、throws

public static void main(String[] args) {
    int a = 1;
    int b = 0;
    try{
        System.out.println(a/b);
    }catch (ArithmeticException e){
        System.out.println("program is exception");
    }catch (Throwable e){
        System.out.println("program is Throwable");
    }finally {
        System.out.printf("finally");
    }
}

// Ctrl + Alt + T 为 try catch 捕获  throw 来抛出异常

public void test() throws ArithmeticException{
    if(b == 0){
        throw new ArithmeticException();
    }
}

4.自定义异常

public class MyException extends Exception{

    private int detail;

    public MyException(int a){
        this.detail = a;
    }

    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}