Thursday, January 30, 2014

How to propagate an exception in java?

This java example demonstrates an exception being propagated. The exception is thrown in M4() but is handled in M2().

Source:

public class PropagateException {

   public static void main(String[] args) {
      M1();
   }

   public static void M1() {
      System.out.println("M1 started");
      M2();
      System.out.println("M1 finished");
   }
  
   public static void M2() {
      System.out.println("M2 started");

      // The Exception thrown in M4() is handled here
      try {
         M3();
      } catch (Exception e) {
         System.out.println("M2: " + e.toString() );
      }

      System.out.println("M2 finished");
   }

   public static void M3() {
      System.out.println("M3 started");
      M4();
      System.out.println("M3 finished");
   }

   public static void M4() {
      System.out.println("M4 started");
      int x = 10 / 0;  // Should throw Exception
      System.out.println("M4 finished");
   }
}

Output:
   $ java PropagateException 
   M1 started
   M2 started
   M3 started
   M4 started
   M2: java.lang.ArithmeticException: / by zero
   M2 finished
   M1 finished

Blog Archive