logging exception and throwing new exception - is it antipattern?

2.6k views Asked by At

If we catch exception and then we throw exception, but not the same type (just based on first one) is it still antipattern to log first one?

Simple example:

    } catch (CloneNotSupportedException e) {
      log.warn(e, e.getMessage());
      throw new InternalError(e.getMessage());
    }
1

There are 1 answers

0
Paul Wasilewski On BEST ANSWER

Catching an exception, create a log message and throwing a new exception is not an anti-pattern at all.

Gernerally, this "pattern" comes into play when you have an interaction/communication which crosses a certain system boundary e.g. a communication between two layers, modules or components. For example this can be a client server interaction, the application layer interacts with the persistence layer or module x calls service of module y.

Let's take a look closer at the actions of the pattern.

Logging the exception? You want to log the exception at the place where it happens. That doesn't means you have to log it right where it happens but at least in your context. Also, think of your logging configuration. You maybe have package, component, system ... related configuration and you want to make sure that you see the exception in the right log.

Throwing a new exception? Generally, a new exception is an abstraction of the old exception. This is useful because the method caller don't have to handle a lot different exceptions. Additionally, you don't want always that the caller see in detail what's happening in your context so using a new exception allows you to hide information.

Catching the exception? Obviously, this is needed that the other actions can be performed.