Java Reference
In-Depth Information
Table 9-1. A Partial List of Methods of the Throwable Class
Method
Description
Throwable getCause()
This method was added in Java 1.4. It returns the cause of the
exception. If the cause of the exception is not set, it returns null .
String getMessage()
It returns the detailed message of the exception.
StackTraceElement[] getStackTrace()
This method was added in Java 1.4. It returns an array of stack trace
elements. Each element in the array represents one stack frame. The
first element of the array represents the top of the stack and the last
element of the array represents the bottom of the stack. The top of
the stack is the method/constructor where the exception object is
created. The object of StackTraceElement class holds information
such as class name, method name, file name, line number, etc.
Throwable initCause(Throwable cause)
It was added in Java 1.4. There are two ways to set an exception as
the cause of an exception. One way is to use the constructor, which
accepts the cause as a parameter. Another way is to use this method.
void printStackTrace()
It prints the stack trace on the standard error stream. The output
prints the description of the exception object itself as the first line
and then the description of each stack frame. Printing stack trace for
an exception is very useful for the debugging purpose.
void printStackTrace(PrintStream s)
It prints the stack trace to the specified PrintStream object.
void printStackTrace(PrintWriter s)
It prints the stack trace to the specified PrintWriter object.
String toString()
It returns a short description of the exception object. The
description of an exception object contains the name of the
exception class and the detail message.
Listing 9-9 demonstrates the use of the printStackTrace() method for an exception class. The main()
method calls the m1() method, which in turn calls the m2() method. The stack frame for this call starts with the
main() method, which will be at the bottom of the stack. The top of the stack contains the m2() method. The output
shows that the printStackTrace() method prints the stack information from top to bottom. Each stack frame
contains the name of the class, the method name, the source file name, and the line number. The first line of the
printStackTrace() method prints the class name of the exception object with a detailed message.
Listing 9-9. Printing the Stack Trace of an Exception
// StackTraceTest.java
package com.jdojo.exception;
public class StackTraceTest {
public static void main(String[] args) {
try {
m1();
}
catch(MyException e) {
e.printStackTrace(); // Print the stack trace
}
}
 
Search WWH ::




Custom Search