条件
(1)异常类必须继承自Exception;
(2)如果想打印自定义的异常类信息,必须重写父类toString方法。
// 自定义异常必须继承自Exception
public class MyException extends Exception{
private static int detail;
public static void main(String[] args) {
}
public MyException(int num) {
super();
detail = num;
}
// 打印自定义异常类的信息
@Override
public String toString() {
return "不合法的参数:"+detail;
}
}
我们来定义一个测试异常类
public class Test {
// test方法如果条件不满足,会抛出我们自定义的异常类
static void test(int num) throws MyException{
if(a > 100) {
throw new MyException(num);
}
System.out.println("没有出现异常");
}
public static void main(String[] args) {
// try() catch() {} 来捕获异常
try {
test(100);
} catch (MyException e) {
System.out.println("异常捕获了 —— "+e);;
} finally {
}
}
}