通常创建子类对象的时候,先会自动创建基类对象。
而如果显式调用基类构造函数时,必须放在构造函数里的第一行。所以,就没有办法捕获到基类构造函数的异常了。以下为示例代码:
class BaseException extends Exception {}
class Base {
Base() throws BaseException {
throw new BaseException();
}
}
class Derived extends Base {
// BaseException must be caught (no way) or
// declared to be thrown:
Derived() throws BaseException {
super();
// not this way, 'catch' without 'try' not allowed:
// catch(BaseException e) {}
// not this way either, because call to super
// must be first statement in constructor:
// try {
// super();
// } catch(BaseException e) {}
}
}
public class Ex21 {
public static void main(String[] args) {
try {
Derived d = new Derived();
} catch(BaseException e) {
System.out.println("BaseException caught in main()");
}
}
}