❮ Previous Next ❯

Java Exception Propagation

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. By default UncheckedExceptions are forwarded in calling chain(propagated).

Let's see a program to understand this concept.

class PropagationDemo
{
void show()
{
int result=50/0;
}
void display()
{
show();
}
void print()
{
try
{
display();
}
catch(Exception e)
{
System.out.println("exception caught");
}
}
class TestPropagation
{
public static void main(String args[])
{
PropagationDemo pd=new PropagationDemo();
pd.print();
}
}
Output

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

Note

By default Checked Exceptions are not forwarded in calling chain(propagated). Let's see a program:

class PropagationDemo1
{
void display()
{
throw new java.io.IOException("device error"); //checked exception
}
void show()
{
display();
}
void print()
{
try
{
show();
}
catch(Exception e)
{
System.out.println("exception handeled");
}
}
public static void main(String args[])
{
PropagationDemo1 pd=new PropagationDemo1();
pd.print();
System.out.println("normal flow");
}
}
Output

Compile Time Error


❮ Previous Next ❯


  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved