Print the stack trace of an exception

By | July 25, 2019

Question

How do I print the stack trace of an exception to a stream other than stderr? One way I found is to use getStackTrace() and print the entire list to the stream.

Solution

Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument:

} catch (Exception ex) {
    ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}

That said, consider using a logger interface like SLF4J with an logging implementation like LOGBack or log4j.

Rate this post

Leave a Reply

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