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 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"); } } }
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"); } } }
Compile time error .