Methods are forbidden to throw RuntimeException
or Exception
. Handling these exceptions requires catching RuntimeException
, which is forbidden in guideline ERR14-J. Catch specific exceptions rather than the more general RuntimeException or ExceptionDo not catch RuntimeException. Moreover, throwing a RuntimeException
can lead to subtle errors, for instance, a caller cannot examine the exception to determine why it was thrown, and consequently cannot attempt recovery.
...
To properly handle the case of passing in a null
string parameter, any code that calls this method must catch RuntimeException
, which violates guideline ERR14-J. Catch specific exceptions rather than the more general RuntimeException or ExceptionDo not catch RuntimeException.
Compliant Solution
This compliant solution throws a specific exception (NullPointerException
) to denote the particular exceptional condition.
...
ERR12-J. Do not log unsanitized user input 06. Exceptional Behavior (ERR) ERR14-J. Catch specific exceptions rather than the more general RuntimeException or ExceptionDo not catch RuntimeException