Java Exceptions Java String Handling

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. It also shows how to convert stack trace to String using Apache commons library.

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


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

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

How to convert stack trace to String in Java?

Stack trace can be converted to String with the help of StringWriter and PrintWriter using printStackTrace method of Throwable class.

This method prints the stack trace to PrintWriter object.


Convert stack trace to String using Apache Commons

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

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

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


Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *