Java Language Pitfall - Excessive or inappropriate stacktraces


Example

One of the more annoying things that programmers can do is to scatter calls to printStackTrace() throughout their code.

The problem is that the printStackTrace() is going to write the stacktrace to standard output.

  • For an application that is intended for end-users who are not Java programmers, a stacktrace is uninformative at best, and alarming at worst.

  • For a server-side application, the chances are that nobody will look at the standard output.

A better idea is to not call printStackTrace directly, or if you do call it, do it in a way that the stack trace is written to a log file or error file rather than to the end-user's console.

One way to do this is to use a logging framework, and pass the exception object as a parameter of the log event. However, even logging the exception can be harmful if done injudiciously. Consider the following:

public void method1() throws SomeException {
    try {
        method2();
        // Do something
    } catch (SomeException ex) {
        Logger.getLogger().warn("Something bad in method1", ex);
        throw ex;
    }
}

public void method2() throws SomeException {
    try {
        // Do something else
    } catch (SomeException ex) {
        Logger.getLogger().warn("Something bad in method2", ex);
        throw ex;
    }
}

If the exception is thrown in method2, you are likely to see two copies of the same stacktrace in the logfile, corresponding to the same failure.

In short, either log the exception or re-throw it further (possibly wrapped with another exception). Don't do both.