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

Koray Tugay :

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 Exception and catch directly and log it?

Nicolas Filotto :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452906&siteId=1