Koray Tugay Koray Tugay - 7 months ago 21
Java Question

Is there any reason to throw an Exception and catch 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 anymore.

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

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


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()) {