Exception Handling with Method Overriding in Java
In our day to day programming we use method overriding widely. Have you ever
considered how exception handling rule works in method overriding? Lets see
how it works in Java with example.
RULE 1. Super class method does not declare any exception in its method
signature.
If super class method does not declared any exception in its method signature
then sub-class's over ridden method can not declare any checked exception
however it can declare any unchecked/RuntimeException. Following example demonstrate the first rule of exception.
Source code (SuperClassExceptionRule1.java)
/** * Example of SuperClassExceptionRule1 in java. * @author javaQuery * @date 2021-09-07 * @Github: https://github.com/javaquery/Examples */ public class SuperClassExceptionRule1 { public void methodWithoutException(){ System.out.println("methodWithoutException"); } public static void main(String[] args) { System.out.printf("SuperClassExceptionRule1"); } public class ChildClassExceptionRule1 extends SuperClassExceptionRule1{ // Compile time error when tried to throw checked exception // @Override // public void methodWithoutException() throws Exception{ // super.methodWithoutException(); // } // Allowed to throw unchecked exception (i.e Any RuntimeException) @Override public void methodWithoutException() throws RuntimeException{ super.methodWithoutException(); } } }RULE 2. Super class method declared exception in its method signature.
If super class method declared any exception in its method signature then
sub-class's over ridden method can declare same exception, any child/sub-class
exception or no exception however you can not declare parent exception. Following example demonstrate the second rule of exception.
Source code (SuperClassExceptionRule2.java)
/** * Example of SuperClassExceptionRule2 in java. * @author javaQuery * @date 2021-09-07 * @Github: https://github.com/javaquery/Examples */ public class SuperClassExceptionRule2 { public void methodWithException() throws IllegalArgumentException{ System.out.println("methodWithException"); } public static void main(String[] args) { System.out.printf("SuperClassExceptionRule2"); } public class ChildClassExceptionRule2 extends SuperClassExceptionRule2 { // Compile time error when tried to throw parent exception // @Override // public void methodWithException() throws Exception{ // super.methodWithException(); // } // Allowed to throw original exception (IllegalArgumentException) // or child exception of IllegalArgumentException @Override public void methodWithException() throws NumberFormatException{ super.methodWithException(); } } public class ChildClassExceptionRule22 extends SuperClassExceptionRule2 { // Allowed not to throw any exception @Override public void methodWithException(){ super.methodWithException(); } } }
0 comments :