In the example below, an exception occurs in the x() method but is not handled. As a result, it propagates to the previous y() method and is again not handled before being handled in the z() method. Any method in the call stack, including the main() method, the z() method, the y() method, and the x() method, can handle an exception. Unchecked exceptions are automatically passed along in the calling chain (propagated).
public class Main { void x(){ int num = 50 / 0; // unchecked exception occurred // exception propagated to y() } void y(){ x(); // exception was passed on to z() } void z(){ try{ y(); // exception handled } catch (Exception e) { System.out.println("exception handeled"); } } public static void main(String args[]){ Main main = new Main(); main.z(); System.out.println("Normal flow of program"); } }
Output:
exception handeled
Normal flow of program
Unlike Unchecked Exceptions, Checked Exceptions do not propagate errors, so the throw keyword must be used in this case. There is no propagation of checked exceptions. Compilation errors are raised by checked exceptions.
In the example below, the compiler will produce a compile-time error if the throws keyword is left out of the x() and y() functions. Because checked exceptions, unlike unchecked exceptions, cannot spread without the throws keyword. Checked exceptions are not by default passed along in the calling chainĀ
import java.io.IOException; public class Main { void x() throws IOException{ // checked exception occurred throw new IOException("Device Error"); // exception passed to y() } void y() throws IOException { x(); // exception passed to z() } void z(){ try { y(); // exception handled } catch (Exception e) { System.out.println("exception handeled"); } } public static void main(String args[]) { Main main = new Main(); main.z(); System.out.println("Normal flow of program"); } }
Output:
exception handeled
Normal flow of program
Post your comment