What is exception propagation? I tried to Google it, but couldn't find satisfactory results. Preferably explain this in terms of Java.
Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method.
unchecked exceptions are automatically propagated in java.
When an exception is raised, the exception-propagation mechanism takes control. The normal control flow of the program stops, and Python looks for a suitable exception handler. Python's try statement establishes exception handlers via its except clauses.
It's explained, surprisingly, in the Java tutorial page about exceptions.
An exception propagates from method to method, up the call stack, until it's caught. So if a()
calls b()
, which calls c()
, which calls d()
, and if d()
throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.
Short answer : Uncaught exceptions are propagated in the call stack until stack becomes empty, this propagation is called Exception Propagation.
Long answer : After a method throws an exception, the runtime system searches the call stack for a method that contains a block of code(exception handler) that can handle the exception. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. Also, there's a note-worthy point:
Lets say, we have a chain of methods where method3() calls method2() and method2() calls method1(). So when
1) An exception occurs in the method3() and in method3() we don’t have any exception handler.
2) Uncaught exception will be propagated downward in stack i.e it will check appropriate exception handler in the method2().
3) Again in method2 if we don’t have any exception handler then again exception is propagated downward to method1() where it finds exception handler.
Example:
class ExceptionPropagation{
void method3(){
int result = 100 / 0; //Exception Generated
}
void method2(){
method3();
}
void method1(){
try{
method2();
} catch(Exception e){
System.out.println("Exception is handled here");
}
}
public static void main(String args[]){
ExceptionPropagation obj=new ExceptionPropagation();
obj.method1();
System.out.println("Continue with Normal Flow...");
}
}
Output :
Exception is handled here
Continue with Normal Flow...
Only unchecked exceptions are propagated. Checked exceptions throw compilation error
[1] http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
[2] http://www.c4learn.com/java/java-exception-propagation/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With