116
Exception Handling with Method Overriding in Java
There are many rules if we talk about method overriding with exception handling.
Some of the rules are listed below:
- If the superclass method does not declare an exception
- If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
- If the superclass method declares an exception
- If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
If the superclass method does not declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.
Let’s consider following example based on the above rule.
TestExceptionChild.java
Output:
Rule 2: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.
TestExceptionChild1.java
Output:
If the superclass method declares an exception
Rule 1: If the superclass method declares an exception, subclass overridden method can declare the same subclass exception or no exception but cannot declare parent exception.
Example in case subclass overridden method declares parent exception
TestExceptionChild2.java
Output:
Example in case subclass overridden method declares same exception
TestExceptionChild3.java
Output:
Example in case subclass overridden method declares subclass exception
TestExceptionChild4.java
Output:
Example in case subclass overridden method declares no exception
TestExceptionChild5.java
Output:
Next TopicCustom Exception