Bug 210130

Summary: False positive "Potential null pointer access" warning after TestCase.fail
Product: [Eclipse Project] JDT Reporter: Nick Radov <nradov>
Component: CoreAssignee: Maxime Daniel <maxime_daniel>
Status: VERIFIED WONTFIX QA Contact:
Severity: normal    
Priority: P3 CC: david_audel, Olivier_Thomann
Version: 3.3.1   
Target Milestone: 3.4 M4   
Hardware: PC   
OS: Windows XP   
Whiteboard:

Description Nick Radov CLA 2007-11-16 13:58:25 EST
Build ID: M20071023-1652

Try the following code.


import java.util.Random;

import junit.framework.TestCase;

public class Test extends TestCase {

    private boolean[] getArray() {
	if (new Random().nextFloat() < 0.5) {
	    return null;
	} else {
	    return new boolean[] { true };
	}
    }

    public void testNull() {
	final boolean[] array = getArray();
	if (array == null) {
	    fail("null");
	}
	for (int i = 0; i < array.length; i++) {
	    System.out.println(array[i]);
	}
    }
}

That code triggers a "Potential null pointer access" on the array.length statement. However, if array == null then the method will have already terminated by calling TestCase.fail(String).
This is similar to Bug 132875 but not exactly the same.
Comment 1 Maxime Daniel CLA 2007-11-17 05:31:23 EST
Thanks for your suggestion. I am afraid our current plans won't allow us to pursue it though. As you noticed, this is much like bug 132875 - a P5 as of today, and would call for an even more specific pattern, tied to JUnit, or for a cross methods analysis to discover that fail will throw an unchecked exception in all cases.

Note that a few workarounds can help you get rid of the unwanted warning, such as:
    public void testNull() {
        final boolean[] array = getArray();
        if (array == null) {
            fail("null");
            return;
        }
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
which makes explicit to us that we exit from within the if block.

Closing as WONTFIX.
Comment 2 David Audel CLA 2007-12-11 07:04:21 EST
Verified for 3.4M4.