Day11-异常

异常 Exception

软件并没完美无缺,软件运行时发生的异常,通常情况下程序可以处理

  1. 检查性异常
  2. 运行时异常,在编译时可能被忽略,被程序员所忽略的异常

错误 Error

脱离程序员控制的问题,错误可以被避免

异常体系结构

img

异常处理机制

捕获异常

抛出异常

异常处理的五个关键字

try catch finally throws throws

public class Main{
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {                                   //监控代码
            System.out.println(a/b);
            new Main().test(a,b);
        } catch (Exception e) {                 //捕获异常
            System.out.println("Exception");
        } finally {
            System.out.println("00");           //一定会执行的代码
        }
        
    }
    public void test(int a ,int b) throws ArithmeticException { //方法直接抛出异常
        if(b==0){
            throw new ArithmeticException();                    //方法中抛出异常
        }
    }
}

自定义异常

public class Main{
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {                                   //监控代码
            new Main().test(a);
        } catch (MyException e) {                 //捕获异常
            System.out.println("Exception"+e);
        } finally {
            System.out.println("00");           //一定会执行的代码
        }

    }
    public void test(int a) throws MyException { //方法直接抛出异常
        System.out.println("传递的参数"+a);
        if(a>10){
            throw new MyException(a);
        }
        System.out.println("OK");
    }
}



public class MyException extends Exception{
    private int detial;

    public MyException(int detial) {
        this.detial = detial;
    }

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

posted @ 2021-02-14 23:15  2月2日  阅读(70)  评论(0)    收藏  举报