问题
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();
}
}
回答1:
Yes - your Example class is effectively declaring:
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. 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.
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.
回答2:
You have to add an explicit constructor with throws clause to the Example class.
public Example() throws Exception {
}
来源:https://stackoverflow.com/questions/23735703/why-default-constructor-cannot-handle-exception-type-exception