Exception propagation in java

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 Unchecked Exceptions are forwarded in calling chain (propagated).


//example of UnChecked Exception propagation
import java.io.*;
class Example {

    public void test()
    {
        int c=1/0;
        System.out.println("Result is "+c);
    }
    public void test1()
    {
        test();
    }
    public void test2()
    {
        test1();
    }
    public void test3()
    {
        try
        {
            test2();
        }catch(ArithmeticException e)
        {
            System.out.println("You are dividing the a number by zero");
            System.out.println(e.getMessage());
        }
    }
    public static void main(String arr[])
    { 
        Example p=new Example();
        p.test3();
    }        
}
You are dividing the a number by zero
/ by zero

Explanation :
In the above example exception occurs in test() method where it is not handled,so it is propagated to previous test1() and test2() method where it is not handled, again it is propagated to test3() method where exception is handled.

//important point

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


//example of Checked Exception propagation
import java.io.*;
class Example {

    public void test()
    {
        /*
        some operation which can cause checked exception
        at run time.
        trying to read data from console using
        BufferedReader class
        */
        InputStreamReader isr=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(isr);
        System.out.println("Enter your name");
        String name=br.readLine();//reading the input from console
        // as line
        System.out.println("Hello Mr. "+name);


    }
    public void test1()
    {
        test();
    }
    public void test2()
    {
        test1();
    }
    public void test3()
    {
        try
        {
            test2();
        }catch(ArithmeticException e)
        {
            System.out.println("Error...");
            System.out.println(e.getMessage());
        }
    }
    public static void main(String arr[])
    { 
        Example p=new Example();
        p.test3();
    }        
}
CompileTime Error.