Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: xferred wrapping CS to ERR14:EX0

...

Using instanceof to check for narrower exceptions in a general catch block is often inadequate because it is frequently impossible to enumerate all possible exceptions that the code could throw.

Compliant Solution (Wrapping)

Occasionally it is necessary to invoke library code that can throw any exception. While it is advisable to redesign the library code to be specific about which exceptions it throws, this is not always possible.

This compliant solution catches any exception thrown, and wraps it inside a custom exception, consequently limiting the exceptions that can be thrown.

Code Block
bgColor#ccccff

class DoSomethingException extends Exception {
  public DoSomethingException(Throwable cause) {
    super( cause);
  }
    
  // other methods
};

private void doSomething() throws DoSomethingException {
  try {
    // code that might throw an Exception
  } catch (Throwable t) {
    throw new DoSomethingException(t);
  }
}

This code is valid by ERR14-EX0 of rule ERR14-J. Do not catch RuntimeException.

Exception wrapping is a common technique to safely handle unknown exceptions, for another example, see rule ERR10-J. Do not let code throw undeclared checked exceptions.

Exceptions

EXC13-EX0: Classes that sanitize exceptions to comply with a security policy are permitted to translate specific exceptions into more general exceptions. This translation could potentially result in throwing RuntimeException or Exception in some cases, depending on the details of the security policy.

...