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.

Output

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.

Output

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.

 

Join 1000+ fellow learners! Enter your email address below: