This question was sparked by a discussion around this article, where I did not receive any good answers.
Why should logging your exception and then rethrowing it (preserving the original stack trace of course) be a bad idea if you can't handle it otherwise?
Log it when you handle it So, better only log the exception when you handle it. Like in the following code snippet. The doSomething method throws the exception. The doMore method just specifies it because the developer doesn't have enough information to handle it.
returning an Exception is indeed an anti pattern becuase Exceptions should be reserved for errors in the execution, not to describe the condition of the service.
Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly. The general principal is to catch the most specific type you can. catch(Exception) is a bad practice because it catches all RuntimeException (unchecked exception) too.
With respect to logging vs. throwing, they're two separate concerns. Throwing an exception will interrupt your execution, prevent any further work, perhaps rollback database commits etc. Logging will simply dump info to the log file (or elsewhere).
I assume the answer is largely because why are you catching it if you can't handle it? Why not let whomever can handle it (or whomever is left with no choice but to handle it) log it, if they feel that it is log-worthy?
If you catch it and log it and rethrow it, then there's no way for the upstream code to know that you've already logged the exception, and so the same exception might get logged twice. Or worse, if all the upstream code follows this same pattern, the exception might be logged an arbitrary number of times, once for each level in the code that decides to catch it, log it, and then throw it again.
Also some might argue that since throwing and catching exceptions are relatively costly operations, all this catching and rethrowing isn't helping your runtime performance. Nor is it helping your code in terms of conciseness or maintainability.
Log-and-throw is a good pattern iff the entity catching and rethrowing the exception has reason to believe that it contains information which will not get logged further up the call stack--at least not in the most-desired fashion. A couple of reasons this may occur:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With