java 自定义异常

1,新建MyException类 自定义 异常类

package exception.demo03;

//自定义 异常类
public class MyException extends Exception {

    //    传递数字 > 10 那么抛出异常
    //接收参数 判断
    private int detail;
    public MyException(int d) {
        this.detail = d;
    }

//    toString
//     异常的打印信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

2,新建Test类

package exception.demo03;

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(1);
        } catch (MyException e) {
            System.out.println("MyException===>"+e);
        }
    }
}

2,运行结果

原文地址:https://www.cnblogs.com/d534/p/15097221.html