29.自定义异常

发布时间 2023-03-22 21:13:08作者: 小黑确实不黑

自定义异常

public class MyException extends Exception{ //继承

    //传递数 >10抛出异常

    private int detail;

    public MyException(int a){

        this.detail = a;

    }

    //alt + insert -> toString:异常的打印信息
    @Override
    public String toString() { //重写方法
        return "MyException{" + detail + '}';
    }
}
public class Test {

    //可能会存在异常的方法
    static void test(int a) throws MyException {

        System.out.println("传递的参数为" + a);

        if(a > 10){
            throw new MyException(a);
        }

        System.out.println("ok");
    }

    public static void main(String[] args) {

        try {
            test(11);
        } catch (MyException e) {
            System.out.println("MyException ->" + e);
        }

    }
}