3

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());
    }
uncleMatuesz
  • 87
  • 1
  • 1
  • 10
  • I think this is a matter of opinion. Some see the whole clone() interface as a bad pattern inherited from Java 1.0. I would be tempted to have a different interface which wraps up this eg. `Copyable` – Peter Lawrey Jan 03 '17 at 12:30
  • 3
    There's lots of cases where you want to catch an exception, log it, and throw a different one. The exception you catch is what's exposed by the code you're calling. The exception you throw is what you want to expose to whoever is calling your code. (This is in general I'm talking about, not the nonsense you have to go through to use `Cloneable`.) – khelwood Jan 03 '17 at 12:30
  • I wouldn't call it an antipattern. I wouldn't log it though since the original exception is wrapped in a new one, so no information gets lost. The caller can now determine if and how to log it. – f1sh Jan 03 '17 at 12:32
  • 4
    I would create the new one with "e" and not "e.getMessage()" in order to keep the stacktrace. – GaspardP Jan 03 '17 at 12:36

1 Answers1

3

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.

Paul Wasilewski
  • 9,762
  • 5
  • 45
  • 49