Java Reference
In-Depth Information
e.fillInStackTrace(); // Record the throw point
throw e; // Rethrow the exception
In practice, it's often more useful to throw an exception of your own. We'll see how to define your own
exceptions in the next section, but first, let's exercise some of the methods defined in the Throwable
class, and see the results.
Try It Out - Dishing the Dirt on Exceptions
The easiest way to try out some of the methods we've just discussed is to make some judicious additions
to the catch blocks in the divide() method we have in the TryBlockTest class example:
public static int divide(int[] array, int index) {
try {
System.out.println("\nFirst try block in divide() entered");
array[index + 2] = array[index]/array[index + 1];
System.out.println("Code at end of first try block in divide()");
return array[index + 2];
} catch(ArithmeticException e) {
System.err.println("Arithmetic exception caught in divide()\n" +
"\nMessage in exception object:\n\t" +
e.getMessage());
System.err.println("\nStack trace output:\n");
e.printStackTrace();
System.err.println("\nEnd of stack trace output\n");
} catch(ArrayIndexOutOfBoundsException e) {
System.err.println("Index-out-of-bounds exception caught in divide()\n" +
"\nMessage in exception object:\n\t" + e.getMessage());
System.err.println("\nStack trace output:\n");
e.printStackTrace();
System.out.println("\nEnd of stack trace output\n");
} finally {
System.err.println("finally clause in divide()");
}
System.out.println("Executing code after try block in divide()");
return array[index + 2];
}
If you recompile the program and run it again, it will produce all the output, as before, but with extra
information when exceptions are thrown in the divide() method. The new output generated for the
ArithmeticException will be:
Message in exception object:
/ by zero
Stack trace output:
java.lang.ArithmeticException: / by zero
at TryBlockTest.divide(TryBlockTest.java:54)
at TryBlockTest.main(TryBlockTest.java:15)
Search WWH ::




Custom Search