为什么默认构造函数无法处理异常类型Exception? [英] Why default constructor cannot handle exception type Exception?
问题描述
我想知道为什么我必须定义一个显式构造函数,因为我收到错误消息,该错误表明默认构造函数无法处理隐式超级构造函数引发的异常类型。
I want to know that why i have to define an explict constructor because i am getting error which says that default constructor cannot handle exception type Exception thrown by implicit super constructor.
class A {
A() throws Exception {
System.out.println("A Class");
}
}
public class Example extends A {
public static void main(String args[]) throws Exception {
Example t = new Example();
}
}
推荐答案
是-您的 Example
类是有效地声明:
public Example() {
super();
}
由于 super( )
调用正在调用 A()
构造函数,该构造函数声明为抛出 Exception
是一个检查的异常。在构造函数中,这就像调用一个方法声明错误一样,这是一个错误,该方法声明它从既不捕获该异常也不声明自己引发该方法的方法内部抛出一个检查过的异常。
That won't compile, because the super()
call is calling the A()
constructor which is declared to throw Exception
, which is a checked exception. That's just as much a mistake in a constructor as it is to call a method which declares that it throws a checked exception from within a method which neither catches the exception nor declares that it throws it itself.
因此,您需要在 Example
的显式声明的构造函数中声明异常。
So you need to declare the exception in an explicitly declared constructor in Example
.
public Example() throws Exception {
super(); // This is implicit; you can remove it if you want.
}
。请注意,这仅在构造函数抛出 checked 异常时才有意义...无需声明未检查的异常,因此编译器提供的默认异常是可以的。
instead. Note that this is only relevant if the constructor throws a checked exception... unchecked exceptions don't need to be declared, so the "compiler-provided" default exception is fine.
还请注意,您不能捕获超级构造函数抛出的异常。
Also note that you can't catch an exception thrown by a super-constructor.
这篇关于为什么默认构造函数无法处理异常类型Exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!