【发布时间】:2013-02-12 06:13:32
【问题描述】:
我正在尝试将 B 类派生到 Java 中的新 C 类。基类构造函数要求必须抛出或捕获未报告的异常。但是如果我尝试将 super(..) 放在 try/catch 中,那么我会被告知对 super 的调用必须是构造函数中的第一条语句。有谁知道解决这个问题的方法吗?
public class C extends B
{
//Following attempt at a constructor generates the error "Undeclared exception E; must be caught or declared
//to be thrown
public C(String s)
{
super(s);
}
//But the below also fails because "Call to super must be the first statement in constructor"
public C(String s)
{
try
{
super(s);
}
catch( Exception e)
{
}
}
}
非常感谢, 克里斯
【问题讨论】:
-
public C(String s) throws Exception? -
是的,您坚持别人的错误决定,即从构造函数中抛出已检查异常。您还将使用已检查的异常定义您的构造函数。
-
如果你想一想,你能做些什么来从异常中恢复?当构造函数抛出异常时,不会创建对象。
标签: java exception constructor derived-class super