Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 557
Koray Tugay Avatar asked Sep 23 '16 17:09

Koray Tugay


1 Answers

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()) {
    ...
}
like image 63
Nicolas Filotto Avatar answered Sep 21 '22 16:09

Nicolas Filotto