Why am I getting unreported exception when the super class default constructor has a 'throws' clause?
class Super {
public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public static void main(String[] args) throws Exception { Sub s = new Sub(); } }
Compile it and you have compile-time error:
Sub.java:6: unreported exception java.lang.Exception in default constructor
public class Sub extends Super { 1 error
Here is a Sun's Bug Report which can answer this question:
When a superclass constructor has a non-empty throws clause, subclasses must define an explicit constructor with an appropriate throws clause, as a default constructor has no throws clause. (This is stated in JLS 2e 8.8.7, ruling out the xxxxx alternative of copying the superclass constructor's throws clause.
Currently, the compiler generates a default constructor with an empty throws clause, and then generates an error message. Unfortunately, the offending call, the implicit call to the superclass constructor, does not appear in the program text, so the message is confusing.
To fix it, you have to explicit to define a default constructor with an appropriate throws clause:
class Super { public Super() throws Exception { System.out.println("Super Class"); } } public class Sub extends Super { public Sub() throws Exception { } public static void main(String[] args) throws Exception { Sub s = new Sub(); } }
Comments
Post a Comment