Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write the exception from printStackTrace() into a text file in Java?

Tags:

java

exception

People also ask

What is the use of printStackTrace () method in Java?

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.

How do you write an exception message in Java?

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.

How do I print exception stack trace in log file?

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.