Pitfall - Excessive or inappropriate stacktraces

suggest change

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.

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Pitfalls - exceptions:
* Pitfall - Excessive or inappropriate stacktraces

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
107 Pitfalls - exceptions
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap