Stack traces are helpful when a Java application throws exception. When the Java application is running in a console, we see the trace in console window. In order to log the trace to a file, we have to capture the stack trace in such a way, so as to be able to print it with the structure in tact. The following Java code snippet, converts a stack trace to String format that can be used to save it to a file.