自定义异常(二)

时间:2022-08-30 20:09:38
package cn.exp;
//自定义异常继承自Exception
//所以在构造方法时采用了super(),也可以直接调用父类的显示异常信息的方法
//注意throw和throw的区别
class ExceptionTest extends Exception {
public ExceptionTest(String errorMessage) {
super(errorMessage);
}
}

class TestExc {
public void show(int a, int b) throws ExceptionTest {
if (b < 0)
throw new ExceptionTest("参数错误");
System.out.println("参数正确;若出错,此句便不会输出");
}
}

public class ExceptionDemo2 {
public static void main(String[] args) {
TestExc testExc=new TestExc();
try {
testExc.show(3, -4);
} catch (ExceptionTest e) {
System.out.println(e.getMessage());//调用父类的显示异常信息的方法

}
}
}