The Superclass.go() method promises the user of the method that it will NOT throw any checked exceptions except the FNFE. Now suppose you override this method and violate the exception specification :
And then, suppose a user does this :
Now, as far as user is concerned, the go() method of var should not throw anything other than FNFE. (Note that var's static type is Superclass). He will write the code that uses var.go() accordingly. However, this would break the declare-or-handle rule for the checked exceptions : The exception that go() is actually throwing is neither declared nor handled by the user.
Hence, in order to avoid surprises, it makes sense that the overridding method doesnot throw any broader checked exceptions than the ones declared by the overridden method.
Originally posted by Vaibhav Chauhan:
Thanks Jasiek and Neelesh ....I agree with you but tell me that if subclass overridding method throw a wider exception (say Exception) whereas the superclass overridden method throw NullPointerException, then compiler should be glad because anyway we are handling NullPointerException (and ofcourse some more exceptions) through "Exception" in subclass overridding method. It ensures that anyhow we are taking care of NullPointerException.
We are not handling, we are throwing. Remember that this rule talks about the exceptions that are thrown - and by "thrown", we mean exceptions that escape the method.
The overridden method can handle any checked and unchecked exceptions with a try-catch block. The rule that you quoted does not apply to exceptions that are "handled" using a try-catch block.