71.

Overview

When exceptional conditions throw exceptions that cannot be easily diagnosed, you may be encountering the Null Flag bug pattern; we discuss how to get your code to throw informative exceptions.

Exceptional conditions in Java programs are ordinarily dealt with by throwing exceptions and catching them at an appropriate point of control. But you will often see methods that indicate such a condition by returning a null value (and perhaps printing a message to System.err). If the calling method does not explicitly check for a null pointer, it may attempt to dereference the return value and trigger a NullPointerException. (For an introduction to null pointers and the NullPointerException, see Chapter 8.) We call this the Null Flag bug pattern. It produces unexpected results that are difficult to debug.

Here's the breakdown of this bug pattern:

  • Pattern: Null Flag.

  • Symptoms: A code block that uses null pointers as flags for exceptional conditions signals a NullPointerException.

  • Cause: The calling methods are not checking for null pointers as return values.

  • Cures and Preventions: Throw exceptions to signal exceptional conditions.

In Chapter 9, we demonstrated how the substitution of null pointers for various base types of data is one of the most common causes of NullPointerExceptions. In this chapter, we will show how substituting null pointers for exceptional conditions also tends to cause problems.

Note 

If the calling method does not explicitly check for a null pointer, it may trigger a NullPointerException.



Bug Patterns in Java
Bug Patterns In Java
ISBN: 1590590619
EAN: 2147483647
Year: N/A
Pages: 95
Authors: Eric Allen

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net