自定义异常
- 图片均来自B站狂神说
代码示例:
package MyException;
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 +
'}';
}
}
package MyException;
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);
}
}
}
/*
输出结果:
传递的参数是:11
MyException=>MyException{detail=11}
*/