Java提供的异常体系不可能预见所有的希望加以报告的错误,所以可以自己定义异常类来表示程序中可能会遇到的特定问题。
如果我们要定义异常类,必须从已有的异常类继承,最好是选择意思相近的异常类继承。
建议新的异常类型最简便的方法就是让编译器为你产生默认构造器,这样就减少了写入代码的量:
//编译器创建了默认的构造器,它将自动调用基类的默认构造器
class SimpleException extends Exception{}
public class InheritingExceptions {
public void f() throws SimpleException{
System.out.println("Throw SimpleException from f()");
throw new SimpleException();
}
public static void main(String[] args) {
InheritingExceptions sed = new InheritingExceptions();
try {
sed.f();
}catch(SimpleException e) {
System.out.println("Caught it!");
}
}
}
结果: