Friday, 9 January 2015

What is Exception Propagation in Java

Exception propagation(forwarding):

An exception is first thrown from the top of the stack and if it is not caught,it drops down the call stack to the previous method,If not caught there, the exception again drops down to the previous method,and so on until they are caught or until they reach the very bottom of the call stack.
This is called exception propagation(forwarding).

Note: By default Unchecked Exceptions are forwarded in calling chain (propagated).

Example of Exception Propagation

class Test{
void divide(){
int data=50/0;
}
void display(){
divide();
}
void run(){
try{
display();
}
catch(Exception e){
System.out.println("exception is handled"); }
}
public static void main(String []args){
Test t1=new Test();
t1.run();
System.out.println("normal flow");
}
}

Output: exception is handled
normal flow

In the above example exception occurs in divide() method where it is not handled,so it is propagated to previous display() method where it is not handled, again it is propagated to divide() method where exception is handled.Exception can be handled in any method in call stack either in main() method,run() method,display()  method or divide() method.

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

For Example:

class Test{
void divide(){
throw new java.io.IOException("IO Exception occur");  //checked exception
}
void display(){
divide();
}
void run(){
try{
display();
}
catch(Exception e){
System.out.println("exception is handled"); }
}
public static void main(String []args){
Test t1=new Test();
t1.run();
System.out.println("normal flow");
}
}

Output: Compile Time Error

No comments:

Post a Comment