This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The overriding method must not throw new or broader checked exceptions than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it�s a subclass of FileNotFoundException.
The overriding method can throw narrower or fewer exceptions. Just because an overridden method �takes risks� doesn�t mean that the overriding subclass� exception takes the same risks. Bottom line: An overriding method doesn�t have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
Hi All, can anybody provide the explanation with a sample program for the above?
It typically refers to the oo paradigm. Typically, a subclass (or an implementing one in case of the overridden method defined in an interface) declares a set of exceptions, that is it defines a 'contract' (i.e. the method signature). When overriding a method, it means that an application wants to define a 'specialized' version of that method. The general contract for overriding is that a child class can do whatever the superclass does, but nothing outside of it. A superclass method must be as more generic as possible (therefore declaring broad exceptions), but a specialized class may not throw ALL the exceptions declared by the superclass, therefore in its signature the subclass is not required to declare all the superclass's methods.
Let's consider the following:
Considering that BroadChildException is a subclass of BroadException, this is valid code, i.e. the subclass can declare an exception which is a subclass of the exception declared in the superclass. The child class can also declare no exception, that is to say: 'I don't care about BroadExceptions at all, because I don't throw it'.
The child class cannot be something like this:
because it declares an exception that its parent doesn't. Now, when programming with OO, you need to understand that super and sub classes are seen as one and a scenario as the above would cause a disalignment between super and subclass.
As a general rule: When defining types and exceptions the child bust be under the parent 'supervision' like in a sandbox.