异常处理

异常处理机制


异常处理五个关键字

try、catch、finally、throw、throws

异常抛出、获取


public class Test {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {//抛出异常程序会继续执行,而不会中断
            new Test().test(a,b);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
//        try{//try监控区域
//           if(b==0){
//               throw new ArithmeticException();
//           }
//            System.out.println(a/b);
//        }
//        catch (Error e){//捕获异常 从小到大类型递进
//            System.out.println("出现error");
//        }
//        catch (Exception e){
//            System.out.println("出现异常");
//        }
//        catch (Throwable e){
//            System.out.println("Throwable");
//        }
//        finally {//处理善后工作 可不加,一般用于处理IO关闭资源占用
//            {
//                System.out.println("finally");
//            }
//        }
    }
//    public static void a(){b();}
//    public static void b(){a();}
    public void test(int a,int b) throws ArithmeticException
    {
        if(b==0){
            if(b==0){
                throw new ArithmeticException();//方法中处理不了异常,则主动抛出异常。
            }
            System.out.println(a/b);
        }
    }

}

自定义异常


package 异常机制;
//自定义的异常类
public class MyException extends Exception {
    //传递数字>10;
    private int detail;
    public MyException(int a) {
       this.detail=a;
    }
    //toString:异常的打印信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
public class Test {

    public static void main(String[] args) {
        //可能会存在异常的方法
        try {
            test(11);
        } catch (MyException e) {
            //增肌处理异常的代码块
            System.out.println(e);
        }
    }
    static void test(int a) throws MyException{
        if(a>10){
                throw new MyException(a);
        }
    }
posted @ 2021-01-17 19:44  爱笑的加油怪  阅读(37)  评论(0)    收藏  举报