第十一话-Java异常

异常:Error和Exception

  1. 简单分类

  1. 异常体系结构

  1. Error

  1. Exception

捕获和抛出异常

package com.xie.exception;

public class Test {
    public static void main(String[] args) {
        try {//try监控区域
            new Test().test(1,0);
        } catch (ArithmeticException e) {//catch捕获异常
            e.printStackTrace();
            System.out.println("aaaaaaaaaa");
        } finally {//处理善后工作
            System.out.println("-------");
        }
    }

    public void test(int a,int b) throws ArithmeticException{
        if(b == 0){
            throw new ArithmeticException();
        }else {
            System.out.println(a/b);
        }
    }
}

注:异常可以捕获多个,但必须从小到大捕获,Throwable>Exception=Error

自定义异常

package com.xie.exception.demo01;

public class MyException extends Exception{

    private int detail;

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

    //异常信息打印
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}
package com.xie.exception.demo01;

public class Test {
    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            e.printStackTrace();//finally执行之后再打印
            System.out.println("MyException-->"+e);
        } finally {
            System.out.println("finally");
        }
    }

    static void test(int a) throws MyException {
        System.out.println("参数:" + a);
        if(a > 10){
            throw new MyException(a);
        }else {
            System.out.println("OK");
        }
    }
}

posted @ 2022-04-10 16:16  少年阿川  阅读(23)  评论(0)    收藏  举报