Kaxhif Khan wrote:"If a method is declared in two or more interfaces, and if that method declares to throw different exceptions in the throws clause, the implementation should list all of these exceptions". I decided to practically check and see what happens
Really like your attitude! Writing little code snippets to see what's happening, is always a good thing to do as it's very instructive.
Kaxhif Khan wrote:What wrong here ? Is the statement in the book wrong or my understanding is wrong ? How can one remove compilation error if he/she face situation like i placed above ...
The statement in the book is completely wrong!
Only if both method declarations in the interfaces define unchecked (runtime) exceptions, the statement in the book is true. Example:
But as you know, with runtime exceptions you don't have to list the exceptions in the method declaration, so this will compile as well:
If both method declarations in the interfaces define a checked exception from a different class hierarchy (like in your original post), your code will only compile if the implementing method defines no checked exceptions in the throws clause (as you discovered yourself):
Every other combination of checked exception(s) will NOT compile (and that's why the statement in the book is completely wrong). As you know the throws clause of the implementing method can list as many runtime exceptions as you want:
If both method declarations in the interfaces define a checked exception from the same class hierarchy (like in your original post), your code will only compile if the implementing method defines no checked exceptions in the throws clause or the most specific checked exception (or one of its subclasses). A few examples to illustrate:
Class
A56A compiles because no checked exceptions are listed in the throws clause. Class
A56B compiles as well, because
IOException IS-A
Exception (and the most specific exception). Class
A56C compiles too, because
FileNotFoundException IS-A
IOException (and a subclass of the most specific exception). And finally class
A56D will not compile, because
Exception isn't the most specific exception.
What if the method declaration in the first interface defines a checked exception and the method declaration in the second interface defines a runtime exception? Your code will only compile if the implementing method defines no checked exceptions in the throws clause.
That was easy, wasn't it?
Hope it helps!
Kind regards,
Roel