Koray Tugay Koray Tugay - 7 months ago 39
Java Question

Is there any reason to throw an 'Exception' and catch it immediately?

This code is from our project, production code:

if (changedToNull) {
try {
throw new Exception();
} catch (Exception e) {
log.debug("changedToNull", e);

The developer does not work with us any more.

Why would someone throw an
and catch directly and log it?

I would also like to note that he was not a junior; he was a senior developer, and this is why I am curious...


For me the main purpose is to get a call stack when you enter in this if block for debugging purpose but it could be rewritten as next:

if (changedToNull) {
    log.debug("changedToNull", new Exception("changedToNull is true"));

Let's say that changedToNull should never be true and you want to get the call stack to understand how it occurred, you could proceed this way.

Creating a call stack is quite expensive so you should make sure that the debug level is enabled by checking the value of isDebugEnabled() too (assuming that you use log4j) as next:

if (changedToNull && log.isDebugEnabled()) {