// Demonstration of the try-catch-finally exception handling mechanism. // // Written: 1/19/06 import java.io.*; public class UsingExceptions1 { public static void main( String args[] ) { System.out.println ("Calling throwsException 0"); try { throwException(0); // call method throwException } // catch Exceptions thrown by method throwException catch ( Exception exception ) { System.err.println( "Exception handled in main" ); } System.out.println (); System.out.println ("Calling throwsException 1"); try { throwException(1); // call method throwException } // catch Exceptions thrown by method throwException catch ( Exception exception ) { System.err.println( "Exception handled in main" ); } System.out.println (); System.out.println ("Calling throwsException2"); try { throwException(2); // call method throwException } // catch Exceptions thrown by method throwException catch ( Exception exception ) { System.err.println( "Exception handled in main" ); } } // demonstrate try/catch/finally public static void throwException(int n) throws Exception { // throw an exception and immediately catch it try { System.out.println( "Method throwException 1 with parameter " + n ); if (n == 0) throw new Exception(); // generate exception if (n == 1) throw new IOException(); System.out.println( "Method throwException 2" ); } // catch exception thrown in try block catch ( IOException exception ) { System.err.println( "IOException handled in method throwException" ); } catch ( Exception exception ) { System.err.println( "Exception handled in method throwException" ); } // this block executes regardless of what occurs in try/catch finally { System.err.println( "Finally executed in throwException" ); } System.err.println( "End of method throwException" ); } // end method throwException } // end class UsingExceptions