The printStackTrace() method in Java is a tool used to handle exceptions and errors. It is a method of Java's throwable class which prints the throwable along with other details like the line number and class name where the exception occurred. printStackTrace() is very useful in diagnosing exceptions.
Following are the different ways to handle exception messages in Java. Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception.
The function printStackTrace() of the Exception class can take one parameter, either a PrintStream or a PrintWriter. Thus, it is possible, using a StringWriter, to print the stack trace into a String: StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e. printStackTrace(pw);
It accepts a PrintStream
as a parameter; see the documentation.
File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
// something
} catch (Exception ex) {
ex.printStackTrace(ps);
}
ps.close();
See also Difference between printStackTrace() and toString()
Try to expand on this simple example:
catch (Exception e) {
PrintWriter pw = new PrintWriter(new File("file.txt"));
e.printStackTrace(pw);
pw.close();
}
As you can see, printStackTrace()
has overloads.
Do set the err/out stream using System
class.
PrintStream newErr;
PrintStream newOut;
// assign FileOutputStream to these two objects. And then it will be written on your files.
System.setErr(newErr);
System.setOut(newOut);
There is an API in Throwable
interface getStackTrace()
which is used internally for printing in console by printStackTrace()
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace()
Try this API to get StackTraceElement
and print those elements sequentially.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With