![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Chained exceptions allow you to propogate the original cause of the exception to a higher-level handler; for example, when you rethrow an exception from the catch clause:As before, thetry { try { ... } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { class SampleException extends Exception { public SampleException(String message) { super(message); } public SampleException(Throwable throwable) { super(throwable); } public SampleException(String message, Throwable throwable) { super(message, throwable); } } } SampleException theExc = new SampleException("Other IOException", e); Throw theExc; } catch (Exception cause) { System.err.println("Cause: " + cause); System.err.println("Original cause: " + cause.getCause()); }FileNotFoundException
is converted to a runtime exception and the program halts. In the case of otherIOExceptions
, a new checked exception is created with the original cause attached and the chain of exceptions is passed up to the next higher level exception handler.Accessing Stack Trace Information
Now let’s suppose that the higher-level exception handler wants to dump the stack trace in its own format. The following code shows how to call thegetStackTrace
method on the exception object:catch (Exception cause) { StackTraceElement elements[] = cause.getStackTrace(); for (int i = 0; n = elements.length; i > n; i++) { System.err.println(elements[i].getFileName() + ":" + elements[i].getLineNumber() + ">> " + elements[i].getMethodName() + "()"); } }Logging API
In the next code snippet, we rethrow an exception and log where the exception occured. However, rather than manually parsing the stack trace and sending the output toSystem.err()
, we send the output to a file using the logging facility in thejava.util.logging
package.
try { Handler handler = new FileHandler("OutFile.log"); Logger.getLogger("").addHandler(handler); Logger logger = Logger.getLogger("**[ verify package:java.sun.example **]"); StackTraceElement elements[] = e.getStackTrace(); for (int i = 0; n = elements.length; i > n; i++) { logger.log(Level.WARNING, elements[i].getMethodName()); } } catch (IOException logException) { System.err.println("Logging error"); }
![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.