Wiki Markup |
---|
Programs must not catch {{java.lang.NullPointerException}}. A {{NullPointerException}} exception thrown at runtime indicates the existence of an underlying {{null}} pointer dereference that must be fixed in the application code (see [EXP11-J. Never dereference null pointers|EXP01-J. Never dereference null pointers]). Handling the underlying null pointer dereference by catching the {{NullPointerException}} rather than fixing the underlying problem is inappropriate for several reasons. First, _avoiding_ the exception by catching {{NullPointerException}} adds significantly more performance overhead than simply adding the necessary checks \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. Second, when there are multiple expressions in a {{try}} block that are capable of throwing a {{NullPointerException}}, it is difficult or impossible to determine which expression is responsible for the exception because the {{NullPointerException}} {{catch}} block handles any {{NullPointerException}} thrown from any location in the {{try}} block. Third, programs rarely remain in an expected and usable state after a {{NullPointerException}} has been thrown. Attempts to continue execution after first catching and logging (or worse, suppressing) the exception rarely succeed. |
...
An acceptable alternative implementation uses a setter method and a getter method to control all interaction with the reference to the current log. The setter ensures use of the null object in place of a null
reference. The getter ensures that any retrieved instance is either an actual logger or a null object (but never a null
reference). Instances of the Null Object are immutable and are inherently thread-safe. Classes that provide setter or getter methods must comply with the second exception of OBJ09OBJ05-J. Defensively copy private mutable class members before returning their references.
...
EXC08-EX0: A catch block may catch all exceptions to process them before rethrowing them (filtering sensitive information from exceptions before the call stack leaves a trust boundary, for example). Refer to ERR06ERR01-J. Do not allow exceptions to expose sensitive information, as well as CWE 7 and CWE 388. In such cases, a catch block should catch Throwable
rather than Exception
or RuntimeException
.
...
Exception wrapping is a common technique to safely handle unknown exceptions. For another example, see rule ERR10ERR06-J. Do not let code throw undeclared checked exceptions.
...