Java Reference
In-Depth Information
public static void m1() throws MyException {
m2();
}
public static void m2() throws MyException {
throw new MyException("Some error has occurred.");
}
}
com.jdojo.exception.MyException: Some error has occurred.
at com.jdojo.exception.StackTraceTest.m2(StackTraceTest.java:20)
at com.jdojo.exception.StackTraceTest.m1(StackTraceTest.java:16)
at com.jdojo.exception.StackTraceTest.main(StackTraceTest.java:7)
Listing 9-9 demonstrates how to print the stack trace of an exception on the standard error. Sometimes you may
need to save the stack trace in a file or in a database. You may need to get the stack trace information as a string in
a variable. Another version of the
printStackTrace()
method lets you do this. Listing 9-10 shows how to use the
printStackTrace(PrintWriter s)
method to print the stack trace of an exception object to a
String
object. The
program is the same as Listing 9-9 with one difference. It stores the stack trace in a string and then prints that string
on the standard output. The method
getStackTrace()
writes the stack trace to a string and returns that string. Please
refer to the chapter on input/output in the topic
Beginning Java Language Features
(ISBN 978-1-4302-6658-7) for
more details on how to use the
StringWriter
and
PrintWriter
classes.
Listing 9-10.
Writing Stack Trace of an Exception to a String
// StackTraceAsStringTest.java
package com.jdojo.exception;
import java.io.StringWriter;
import java.io.PrintWriter;
public class StackTraceAsStringTest {
public static void main(String[] args) {
try {
m1();
}
catch(MyException e) {
String str = getStackTrace(e);
// Print the stack trace to the standard output
System.out.println(str);
}
}
public static void m1() throws MyException {
m2();
}