Javatpoint Logo
Javatpoint Logo

ExceptionHandling with MethodOverriding in Java

There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:
  • 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

1) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.

Test it Now
Output:Compile Time Error

2) Rule: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.

Test it Now
Output:child

If the superclass method declares an exception

1) Rule: If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent exception

Test it Now
Output:Compile Time Error

Example in case subclass overridden method declares same exception

Test it Now
Output:child

Example in case subclass overridden method declares subclass exception

Test it Now
Output:child

Example in case subclass overridden method declares no exception

Test it Now
Output:child
Next TopicCustom Exception




Please Share

facebook twitter google plus pinterest tumbler

Latest 4 Tutorials