|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Chained exceptions allow you to rethrow an exception, providing additional information without losing the original cause of the exception. The chained exception API was introduced in 1.4 by adding acauseproperty of typeThrowableto exceptions. Two methods and two constructors were added toThrowable, the class from which all exceptions inherit. Since everyThrowablecan have a cause, each exception can have a cause, which itself can have a cause, and so on.The following are the methods and constructors in
Throwablethat support chained exceptions.TheThrowable getCause() Throwable initCause(Throwable) Throwable(String, Throwable) Throwable(Throwable)Throwableargument toinitCauseand theThrowableconstructors is the exception that caused the current exception.getCausereturns the exception that caused the current exception, andinitCausereturns the current exception.The following example shows how to use a chained exception.
In this example, when antry { } catch (IOException e) { throw new SampleException("Other IOException", e); }IOExceptionis caught, a newSampleExceptionexception is created with the original cause attached and the chain of exceptions is thrown 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 the
Definition: A stack trace provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred. A stack trace is a useful debugging tool that you'll normally take advantage of when an exception has been thrown.getStackTracemethod 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
The next code snippet logs where an exception occurred from within thecatchblock. However, rather than manually parsing the stack trace and sending the output toSystem.err(), it sends the output to a file using the logging facility in thejava.util.loggingpackage (added in the 1.4 release of the Java platform).
try { Handler handler = new FileHandler("OutFile.log"); Logger.getLogger("").addHandler(handler); } catch (IOException e) { Logger logger = Logger.getLogger("package.name"); StackTraceElement elements[] = e.getStackTrace(); for (int i = 0; n = elements.length; i < n; i++) { logger.log(Level.WARNING, elements[i].getMethodName()); } }
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.