Question is we cannot use throws clause with overridden method definition if parent method does not have any. Why ?
public void show()
public void show () throws IOException // this line will fail to compile
I was wondering how can we achieve this without touching base class's method, Since there is possibility that overridden method's implementation can throw checked exception and we don't want to handle in same method and want that to be thrown to calling method .
This is why it isn't allowed. Consider the following code (and this code assumes that Child extends Parent, which it doesn't in your code, but I think you meant it to).
Line 1 is fine. A Child IS-A Parent in this context, so the compiler will accept it.
Line 2 is fine. The compiler will only consider the reference type of the variable, and that is Parent. Parent.show() does not declare any checked exceptions.
But because we've allowed show() to be overridden to throw additional checked exceptions, there's a chance that this call could in fact throw an IOException. Which means we now have an unhandled checked exception - but the compiler is supposed to prevent this from happening. The problem is caused by the method being overridden in that way. So instead, the compiler doesn't allow it.
This is an example of the general principle (the "substitution principle") that instances of subclasses should be usable whenever an instance of the superclass is expected. Allowing overriding like that would break this principle.
Joined: Sep 04, 2012
Thanks Matthew Brown Here is my understanding
1) To achieve polymorphism we cannot compromise with checked exception handling rule. since checked exceptions are supposed to handled properly and if not should not surpass the compilation.
2) substitution principle
Because IOException is check exception and in parent class's show() method we did not throws IOException or it's super class (Exception) hence we can not throws IOException or it's sub class in Child class's show() method