Exception Propagation in Java

Whenever methods are called stack is formed and whenever an exception is first thrown from the top of the stack and if it is not caught, it starts coming down the stack to previous methods until it is not caught.
If exception remains uncaught even after reaching bottom of the stack it is propagated to JVM and program is terminated.

Propagating unchecked exception :
Rule: By default Unchecked Exceptions are forwarded(propagated) in calling chain.

package com.blog;

public class UncheckedExPropagation {

public void method1() {
try{
method2();
}catch(ArithmeticException ex){
System.out.println(“Exception Caught here”); // Exception is caught here
}
}

public void method2() {
method3();
}

public void method3() {
int i=5/0;// Exception occurred here
}

public static void main(String[] args) {
UncheckedExPropagation uncheckedExPropagation = new UncheckedExPropagation();
uncheckedExPropagation.method1();
}

}

Output
Exception Caught here

Screen Shot 2017-04-22 at 6.22.40 PM

Let’s see step by step what happened in above program
JVM called main method
step 1 – main called method1()
step 2 – method1 called method2()
step 3 – method2 called method3()
step 4 – Arithmetic exception occurred in method3 and it is automatically propagated exception to method2() [because, unchecked exceptions are propagated automatically]
step 5 – method2 automatically propagated exception to method1() [because, unchecked exceptions are propagated automatically]
step 6 – method1 handled the exception using try and catch.

Propagating checked exception

Rule: By default, Checked Exceptions are not forwarded(propagated) in calling chain.

package com.blog;

public class checkedExPropagation {

public void method1(){
try {
method2();
} catch (ClassNotFoundException e) {
System.out.println(“ClassNotFoundException caught here”);
}
}

public void method2() throws ClassNotFoundException {
method3();
}

public void method3() throws ClassNotFoundException {
Class.forName(“test.blog.TestClass”);// ClassNotFoundException is thrown here
}

public static void main(String[] args) throws ClassNotFoundException {
checkedExPropagation checkedExPropagation = new checkedExPropagation();
checkedExPropagation.method1();
}

}

Output
ClassNotFoundException caught here

Let’s see step by step what happened in above program
JVM called main method
step 1 – main called method1()
step 2 – method1 called method2()
step 3 – method2 called method3()
step 4 – ClassNotFoundException is thrown in method3 and is propagated to method2() using throws keyword.[Because, checked exceptions are not propagated automatically]
step 5 – method2 propagated exception to method1() using throws keyword.[Because, checked exceptions are not propagated automatically]
step 6 – method1 handled the exception using try and catch.

Leave a Reply

Your email address will not be published. Required fields are marked *