Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: code tweaks

...

Code Block
bgColor#FFcccc
try {
    doSomething();
} catch (ExceptionThrowable e) {
  String msg = e.getMessage();
  switch (msg) {
    case "stack underflow":
      // ...handle error
      break;
    case "connection timeout":
      // ...handle error
      break;
    case "security violation":
      // ...handle error
      break;
    default throw e;
  }
}

If doSomething throws an exception whose type is a subclass of Exception with the message "stack underflow," the appropriate action will be taken in the exception handler. However, any change to the literals involved will break the code. For example, if a maintainer were to edit the throw expression to read throw new Exception("Stack Underflow");, the exception would be rethrown by the code of the noncompliant code example rather than handled. AlsoFinally, exceptions may be thrown without a message.

This noncompliant code example falls under ERR08-EX0 of rule ERR08-J. Do not catch NullPointerException or any of its ancestors.

Compliant Solution

It is better to use existing specific exception types or to define new special-purpose exception types:

Code Block
bgColor#ccccff
public class StackUnderflowException extends Exception {
  StackUnderflowException () {
    super();
  }
  StackUnderflowException (String msg) {
    super(msg);
  }
}

// ...

try {
    doSomething();
} catch (StackUnderflowException sue) {
  // handle ...error
} catch (TimeoutException te) {
  // handle ...error
} catch (SecurityException se) {
  // ...
} catch(Exception e) {
  // ...
  throw e;handle error
}

Applicability

Exceptions are used to handle exceptional conditions. If an exception is not caught, the program will be terminated. An exception that is incorrectly caught or is caught at the wrong level of recovery will often cause incorrect behavior.

...