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();
}
}
Further Reading
8.8.9 Default Constructor In the Java Language Specification 3rd Edition
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?