Java Exception Propagation

When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting immediately behind the peek method. If the exception is not caught, then again, it goes down to the next previous method, and the propagation continues till the exception is caught.The list of the methods that are present in the stack is called as call stack, whereas the process by which an exception propagates from peak to bottom of a stack is known as the Java Exception Propagation.

Propagation in Unchecked Exception

By default, Java facilitates the propagation of an unchecked exception in the call stack. Let’s confirm the same with the help of the following program.

FileName: ExceptionPropagationExample.java

Output:

Java Exception Propagation

Explanation:The method m3() invokes the method m2(), which in turn invokes the method m1(). In the method m1(), an unchecked exception is raised. The Java runtime system tries to tackle the exception. However, the system finds no code to handle the exception in m1(). Therefore, it goes down the stack and looks for the exception handling code in m2(). However, this time also, the search goes in vain, and the search continues in the bottom last method present in the stack, and this time the code handling the exception is found, which handles the raised exception of the method m1(). The call stack is described in the following diagram.

Java Exception Propagation

Propagation inchecked Exception

In the checked exception, the propagation of exception does not occur by default. Observe the following program.

FileName: ExceptionPropagationExample1.java

Output:

Java Exception Propagation

Explanation:The output confirms that the program has not terminated normally. It is because the checked exception raised in the method m1() has not been handled. We also see that m3() is willing to handle the exception using the try-catch block. However, the IOException raised in the m1() method never gets propagated to the method m3(). Thus, we see that the checked exception does not propagate on its own.

Forcing the Propagation in the Checked Exception

There can be a scenario when one needs to propagate the checked exception. To achieve the same, one needs to use the throws keyword. The following program illustrates the same.

FileName: ExceptionPropagationExample2.java

Output:

Java Exception Propagation

Explanation:We observer that the program terminated normally. It happened because of the throws keyword. The throws keyword provides the path to the raised exception from the method m1() to m3() via method m2().

Pin It on Pinterest

Share This