Source of TestMyException.java


  1: //TestMyException.java
  2: //Demonstrates use of programmer-defined exceptions and a stack trace.

  4: import java.io.*;


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


 16: class TestMyException
 17: {
 18:     static PrintWriter screen = new PrintWriter(System.out, true);


 21:     static public void main(String[] args)
 22:     {
 23:         try
 24:         {
 25:             methodA();
 26:         }
 27:         catch(MyException me)
 28:         {
 29:             screen.println("\nThe exception has been caught in main.");
 30:             screen.println("The stack trace shows the order in which");
 31:             screen.println("each method has thrown the exception.\n");
 32:             me.printStackTrace(screen);
 33:         }
 34:     }


 37:     static void methodA()
 38:     throws MyException
 39:     {
 40:         methodB();
 41:     }


 44:     static void methodB()
 45:     throws MyException
 46:     {
 47:         methodC();
 48:     }


 51:     static void methodC()
 52:     throws MyException
 53:     {
 54:         //An exception must be instantiated before
 55:         //it can exist, after which it may be thrown.
 56:         throw new MyException();
 57:     }
 58: }