0

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? Thanks

6
  • 1
    It's not clear what you're asking. Are you asking why Child can't have throws FileNotFoundException instead of throws IOException? Commented May 11, 2016 at 8:12
  • @T.J.Crowder: My question is: Why constructor and method is different about the way throws level of Exception? Commented May 11, 2016 at 8:14
  • 2
    @duy the child constructor has an implicit super() call therefore it must at least declare the exceptions of the parent constructor. This is not the case when you overwrite a method and do not invoke the super method. Commented May 11, 2016 at 8:15
  • That's still not clear. Perhaps show, in code, what you're trying to do and what error you get. Commented May 11, 2016 at 8:16
  • @T.J.Crowder: My question is: Why constructor and method is different about the way throws level of Exception? Commented May 11, 2016 at 8:28

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You told "you can call super explicitly and wrap it in a try ... " I think it should not compile as Constructor call must be the first statement in a constructor.
@TJCrowder unfortunately one cannot wrap the super call in a try-catch :-(
2

As per your code, looks like there are two parts in your question and their answer is as below-

  1. For the constructor you have to specify broader or equal level of checked exception. For unchecked exception it's different case.

  2. The overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.