Source of TestRethrowing.java


  1: //TestRethrowing.java
  2: //Demonstrates re-throwing and exception, and the use of a stack trace.

  4: import java.io.*;


  7: class MyException extends Throwable
  8: {
  9:     public MyException(){super();}
 10:     public MyException(String s){super(s);}
 11: }


 14: class TestRethrowing
 15: {
 16:     static PrintWriter screen = new PrintWriter(System.out, true);

 18:     static public void main(String[] args)
 19:     {
 20:         try
 21:         {
 22:             methodA();
 23:         }
 24:         catch(Throwable t)
 25:         {
 26:             screen.println(t.toString() + " Caught in method main.");
 27:             t.printStackTrace();
 28:             screen.println();
 29:         }
 30:     }


 33:     static void methodA()
 34:     throws Throwable
 35:     {
 36:         methodB();
 37:     }


 40:     static void methodB()
 41:     throws Throwable
 42:     {
 43:         try
 44:         {
 45:             methodC();
 46:         }
 47:         catch(MyException me)
 48:         {
 49:             screen.println(me.toString() + " Caught in methodB.");
 50:             me.printStackTrace();
 51:             screen.println();
 52:             throw me.fillInStackTrace();
 53:             //Supplies information for the trace and
 54:             //returns an object of type this.Throwable
 55:         }
 56:     }


 59:     static void methodC()
 60:     throws MyException
 61:     {
 62:         methodD();
 63:     }


 66:     static void methodD()
 67:     throws MyException
 68:     {
 69:         methodE();
 70:     }


 73:     static void methodE()
 74:     throws MyException
 75:     {
 76:         //An exception must be instantiated before
 77:         //it can exist, after which it may be thrown.
 78:         throw new MyException("This is my own exception.");
 79:     }
 80: }