诊断Java代码: 空标志错误模式2011-02-11 IBM Eric E. Allen空标志错误模式在我的上一篇文章中,我说明了用空指针代替各种不同基本类型的数据是如何成为引起 NullPointerException 异常最普遍的原因之一的。这一次,我将说明用空指针代替异常情况怎么也会导致问题的出现。在 Java 程序中,异常情况通常是通过抛出异常,并在适当的控制点捕获它们来进行处理。但是经常看到的方法是通过返回一个空指针值来表明这种情况(以及,可能打印一条消息到 System.err )。如果调用方法没有明确地检查空指针,它可能会尝试丢弃返回值并触发一个空指针异常。您可能会猜想,之所以称这种模式为空标志错误模式,是因为它是不一致地使用空指针作为异常情况的标志引起的。起因让我们来考虑一下下面的这个简单的桥类(从 BufferedReaders 到 Iterators ):import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Iterator; public class BufferedReaderIterator implements Iterator { private BufferedReader internal; public BufferedReaderIterator(BufferedReader _internal) { this.internal = _internal; } public boolean hasNext() { try {
boolean result = true; // Let"s suppose that lines in the underlying input stream are known // to be no greater than 80 characters long. internal.mark(80); if (this.next() == null) { result = false; } internal.reset(); return result; } catch (IOException e) { System.err.println(e.toString()); return false; } } public Object next() { try { return internal.readLine(); } catch (IOException e) { System.err.println(e.toString()); return null; } } public void remove() { // This iterator does not support the remove operation. throw new UnsupportedOperationException(); } }