Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
A method should rarely throw {{RuntimeException}} or {{Exception}}. This is because handling these exceptions requires catching {{RuntimeException}}, which is forbidden in [EXC14-J. Catch specific exceptions as opposed to the more general RuntimeException]. Moreover, throwing a {{RuntimeException}} can lead to subtle errors, suchfor asinstance, a caller who fails to retrieve a return value from an offending method, is unable to check for appropriate feedback. The Java Language Specification (Section 8.4.7 Method Body) allows the declaration of a method with a return type without making it necessary to return a value if a runtime exception is thrown from within the method \[[JLS 05|AA. Java References#JLS 05]\].

...

Compliant Solution

This compliant solution devotes catches a specific exception (NullPointerException) to denote the particular exceptional condition.

...

Code Block
bgColor#ffcccc
private void doSomething() throws Exception {
  //...
}

Compliant Solution

...

Code Block
bgColor#ccccff
private void doSomething() throws IOException {
  //...
}

Using instanceof to check for narrower exceptions in a general catch block is not always helpful because it is usually impossible to enumerate all the exceptions that the code is capable of throwing.

...