12

I just started using the new Eclipse 4.2 (Juno) Null Analysis.

On code like this:

x = foo();
if (x == null)
    fail("x is null");
return x.bar();

I'm getting warnings that x may be null. But it can't be, because fail always throws and therefore never returns. (With better inter-procedural analysis it could presumably determine this automatically, but it currently doesn't seem to.)

Obviously, there are ways to rewrite the code to get around the warning, but what I'd like is a way to indicate (e.g. an annotation) that fail never returns.

I also tried to suppress the warning with @SuppressWarnings("null") but that didn't work.

One way to get rid of the warning is to add: assert x != null; (assuming you have turned on the setting to include asserts in null analysis)

In GCC C++ I can do: void fn __attribute__ ((noreturn))

Andrew McKinlay
  • 2,431
  • 1
  • 24
  • 27

2 Answers2

15

One semi-traditional way to do this is as follows:

public RuntimeException fail(String message) {
  throw new RuntimeException(message);
}

so you can write throw fail("x is null"). Of course, fail will always end up doing the throwing, not the throw, but it's enough to reassure the compiler that that line will always throw.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

have you tried org.eclipse.jdt.annotation.Nullable annotation?

http://git.eclipse.org/c/jdt/eclipse.jdt.core.git/tree/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/Nullable.java

Gergely Szilagyi
  • 3,813
  • 1
  • 14
  • 12