javacodex.com
Java Examples
Java Examples
memu home questions

Rethrowing Exceptions

This java example demonstrates how to rethrow an exception.

M2() throws an exception and M1() handles it and then rethrows it.

Source: (RethrowException.java)

class MyException extends Exception { }
 
public class RethrowException {
 
   public static void main(String[] args) {
 
      try {
         M1();
      } catch (Exception e) {
         System.out.println("main(): Caught "  + e.toString());
      }
   }
 
   public static void M1() throws MyException {
      try {
         M2();
      } catch (Exception e) {
         System.out.println("M1(): Caught " + e.toString());
 
         System.out.println("M1(): Rethrowing " + e.toString());
         throw e;
      }
   }
 
   public static void M2() throws MyException {
      System.out.println("M2(): Throwing MyException...");
      throw new MyException();
   }
}
 

Output:

$ java RethrowException 
M2(): Throwing MyException...
M1(): Caught MyException
M1(): Rethrowing MyException
main(): Caught MyException

Contact: javacodex@yahoo.com