[英]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. 我想知道为什么我必须定义一个显式构造函数,因为我收到错误消息,该错误表示默认构造函数无法处理由隐式超级构造函数引发的异常类型Exception。
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();
}
}
Yes - your Example
class is effectively declaring: 是-你的Example
类是有效的声明:
public Example() {
super();
}
That won't compile, because the super()
call is calling the A()
constructor which is declared to throw Exception
, which is a checked exception. 那不会编译,因为super()
调用正在调用A()
构造函数,该构造函数声明为抛出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. 在构造函数中,这就像调用一个方法声明一个错误一样,该方法声明它从既不捕获该异常也不声明自己引发该方法的方法内部抛出一个已检查的异常。
So you need to declare the exception in an explicitly declared constructor in Example
. 因此,您需要在Example
中的显式声明的构造函数中声明异常。
public Example() throws Exception {
super(); // This is implicit; you can remove it if you want.
}
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. 另请注意,您无法捕获由超级构造函数引发的异常。
You have to add an explicit constructor with throws
clause to the Example class. 您必须在Example类中添加带有throws
子句的显式构造函数。
public Example() throws Exception {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.