Home » Exception Handling with Method Overriding in Java

Exception Handling with Method Overriding in Java

by Online Tutorials Library

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:

Exception Handling with Method Overriding in Java

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:

Exception Handling with Method Overriding in Java

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:

Exception Handling with Method Overriding in Java

Example in case subclass overridden method declares same exception

TestExceptionChild3.java

Output:

Exception Handling with Method Overriding in Java

Example in case subclass overridden method declares subclass exception

TestExceptionChild4.java

Output:

Exception Handling with Method Overriding in Java

Example in case subclass overridden method declares no exception

TestExceptionChild5.java

Output:

Exception Handling with Method Overriding in Java


Next TopicCustom Exception

You may also like