duy duy - 1 year ago 75
Java Question

Inheritance of exception in method and contructor in java

I have code:

class Father {
public Father() throws IOException {}
public void foo() throws IOException {}

class Child extends Father {
//If use FileNotFoundException here, compile fail
public Child() throws Exception {}

//If use Exception here, compile fail
public void foo() throws FileNotFoundException {}

When writing child's constructor, we must throw at least exception of father's constructor or super exception (IOException -> Exception).
However, to child's method, it must throw child exception (IOException -> FileNotFoundException).
Why it occurs in Java. Please explain it?

Answer Source

If you override a method and do not invoke the super method you may narrow the exception

public class Child {
    public void foo() throws FileNotFoundException {
         // overrides Parent.foo() throws IOException

But in the case of the constructor, an implicit super() call to the parent constructor is inserted, and therefore the child constructor must also at least declare all checked exceptions of the parent constructor.

Alternately, you can call super explicitly and wrap it in a try that handles the exceptions you want to handle:

public Child() throws FileNotFoundException {
    try {
    } catch (IOException ioe) {
        // Handle the IOException...
    // ...do something that may throw FileNotFoundException
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download