通常创建子类对象的时候,先会自动创建基类对象。
而如果显式调用基类构造函数时,必须放在构造函数里的第一行。所以,就没有办法捕获到基类构造函数的异常了。以下为示例代码:
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()");
}
}
}
探讨Java子类构造异常捕获与基类构造函数调用
本文深入分析了在Java中创建子类对象时,如何正确调用基类构造函数并捕获异常,强调了构造函数调用顺序的重要性,并通过示例代码展示了解决方案。
3149

被折叠的 条评论
为什么被折叠?



