Community
Participate
Working Groups
The following snippet raises a warning which is trivially incorrect: WARN: The variable result can only be null; it was either set to null or checked for null when last used. public class Test { public static Object foo() { Object result = null; try { result = new Object(); } catch (Exception e) { result = null; } return result; } }
Copying the test case to label lines: public class Test { public static Object foo() { Object result = null; // a try { result = // b new Object(); // c } catch (Exception e) { result = null; // d } return result; } } The only way to get to line d is to get an exception while executing line c, in effect skipping the assignment line b. Since line a assigns null to result, result is still null line d.
BTW, this may come from a simplification of your original test case. We do have a few issues when try/catch and loops are involved.
Okay, so the test was actually too minimal. Here's a slightly expanded test for which your analysis does not hold: public static class Test2 { public static Object foo() { Object result = null; try { result = new Object(); // a' result = new Object(); // b' } catch (Exception e) { result = null; // c': warning here } return result; } } Now control can arrive at c' if an exception is raised by b', which is after the assignment at a'. But that does seem awfully pedantic. Here are some examples which are closer to the originally problematic code: public static class Test3 { public static Object foo(java.sql.ResultSet rs) { Object result = null; try { while (rs.next()) { result = rs.getObject(1); // a'' } } catch (Exception e) { result = null; // b'': arrive here after possibly many // assignments at a'' } return result; } } public static class Test4 { public static Object foo(java.sql.ResultSet rs) { Object result = null; try { result = new Object(); // a''' bar(); } catch (Exception e) { result = null; // b''': arrive here when a RuntimeException // is raised at c''', which follows the // assignment at a''' } return result; } private static void bar() { throw new RuntimeException(); } }
These are valid test cases, thanks. Reopening.
Released NullReferenceTest # 564 to 566. These tests succeed as fixed by the fix of bug 150082, hence I'll close this bug as a duplicate. Moreover, my initial answer to comment #1 was wrong. An exception could happen at the end of the assignment that should be caught by the Exception catch, hence the first test case should not complain either. This is reflected in NullReferenceTest # 564. *** This bug has been marked as a duplicate of 150082 ***
Changing OS from Mac OS to Mac OS X as per bug 185991