< Prev
Next >

Exception Propagation

Do you know what happens when an exception occurs in our program and how it travels through our program after it is originated? Let's continue reading to know about how exactly an exception propagates through our code after it is raised.

What happens when an exception is thrown by the program?

Considering a scenario, in which your program starts its execution at the main() method, main() calls method1(), method1() calls method2(), method2() calls method3(), now the call stack should look like the figure below-:

The currently executing method is at the top of the call stack, which in this example is method3(). Let's say while executing method3(), an exception is raised/thrown. Now this exception is thrown down to the next method in the call stack, i.e. method2(), which in turn throws the exception down to next method in the call stack, i.e. method1(). The process continues until the exception is thrown to the method at the bottom of the call stack, i.e. main() method.
Now, at this time call stack explodes which leads to the abrupt termination of the program.

Exception propagation example

class Exp
public static void main(String... ar)
Exp ob = new Exp();

public void method1()

public void method2()

public void method3()
	System.out.println(100/0);	//ArithmeticException is raised/thrown by the program.
	System.out.println("Hello"); //This statement will not be executed.


Output -:

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Exp.method3(Exp1.java:23)
        at Exp.method2(Exp1.java:17)
        at Exp.method1(Exp1.java:12)
        at Exp.main(Exp1.java:6)

In the code above, an integer number(100) is divided by a zero, which leads to an unchecked exception of type ArithmeticException thrown at the runtime by Java interpreter. This exception is thrown when method3() is being executed, method3() throws this exception down to the next method in the call stack, i.e. method2() and the process continues until this exception reaches the method at the bottom of the call stack, i.e. main() method. At this time, program terminates abruptly, without executing the statement that had to print a Hello message.

Hence, it is important to handle the exception in a program, so that an exception doesn't alter the normal flow of the program and ends it unexpectedly.

The process of handling an exception in a program is called Exception Handling. We will learn about strategy of Exception Handling in the next article.

Please share this article -

Facebook Google Pinterest Reddit Tumblr Twitter

< Prev
Next >
< Unchecked Exception
Try-Catch block >

Please Subscribe

Please subscribe to our social media channels for daily updates.

Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page