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))
Return parameter If the method does not return a value we use the void Java keyword.
A method does not have to return something, but all methods need to have a return type. The return type tells Java what type of value it can expect the method to return, the void type is just there to tell Java that the method does in fact not return anything.
Returning a Value from a Method If a method does not return a value, it must be declared to return void . However, the pop() method in the Stack class returns a reference data type: an object. Methods use the return operator to return a value. Any method that is not declared void must contain a return statement.
Yes, it will end the method once a value is returned.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With