Skip to content

Convert stack trace to String Java Example

Convert stack trace to string Java example shows how to convert exception stack trace to string in Java using the StringWriter, PrintWriter classes, and Apache commons library.

The stack trace is useful to debug the code and see from where exactly the exception was originated and the root cause of the problem. Stack trace of the exception can be printed using the printStackTrace method. Consider the below-given code example.

Output

By looking at the stack trace, we can know that the exception was originated from the method3 which then propagated to the method2 and method1 and finally caught in the main method where we printed the exception stack trace using the printStackTrace method in the catch block.

Sometimes instead of printing the stack trace, we want to convert the stack trace to the string for storing it or for writing it to the log file.

How to convert stack trace to String in Java?

The stack trace can be converted to a string with the help of the StringWriter and PrintWriter classes using the printStackTrace method of the Throwable class.

The printStackTrace method prints the stack trace to the PrintWriter object.

Output

Using Apache Commons

If you are using the Apache Commons library, you can use the getStackTrace method of the ExceptionUtils class to convert the stack trace to string.

This method gets the stack trace from the Throwable object as a string as given below.

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.