Exception Propagation in java

In the previous post, we have seen difference between final, finally and finalize. In this post, we will see what is exception propagation?

What is Exception propagation?

Exception can occur at any step in the program and there should be proper exception handling. Exception is thrown from the top of the stack, if it is not caught then it will drop down in the call stack and look in previous method if exception is caught there or not. If exception is not caught there also , then it will drop down to previous method and like wise it goes on .. unless the exception is caught.

Suppose we have 4 methods m1,m2,m3 and m4. If exception occurs in m4 but exception is not handled there. It will drop down to m3 to check if exception is handled there. Consider exception is handled in m1, then it will come till m1 and handle the exception.

Exception Propagation

Exception are propagated for unchecked exceptions:

For unchecked exceptions , exceptions are propagated. Let’s understand with an example.

class ExceptionPropagationEx{	
	 
     public static void main(String args[]){  
    	 ExceptionPropagationEx exp=new ExceptionPropagationEx();  
	     exp.m1();
	     System.out.println("Executing normal flow..");  
	 } 

	 void m4(){
		 int i = 20/0;
	 }
	 
	 void m3(){
		 m4();
	 }
	 
	 void m2(){
		 m3();
	 }
	 
	 void m1(){
		 try{
			 m2(); 
		 }catch(Exception e){
			 System.out.println("Exception is handled in m1");
		 }		 
	 }
 
}
Output:
Exception is handled in m1
Executing normal flow..

Exception are not propagated for checked exceptions:

Exception are not propagated for checked exception like IOException,SQLException etc. Let’s see with the example.

class ExceptionPropagationEx{	
	 
     public static void main(String args[]){  
    	 ExceptionPropagationEx exp=new ExceptionPropagationEx();  
	     exp.m1();
	     System.out.println("Executing normal flow..");  
	 } 

	 void m4(){
		 throw new java.io.IOException("Checked Exception..");  //compile time error
	 }
	 
	 void m3(){
		 m4();
	 }
	 
	 void m2(){
		 m3();
	 }
	 
	 void m1(){
		 try{
			 m2(); 
		 }catch(Exception e){
			 System.out.println("Exception is handled in m1");
		 }		 
	 }
 
}
Output:
Compile time error .
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.

 

 

Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...