Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to mark (e.g. annotate) a Java method as never returning?

Tags:

java

eclipse

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))

like image 558
Andrew McKinlay Avatar asked Jun 28 '12 17:06

Andrew McKinlay


People also ask

How do you write a method that does not return anything Java?

Return parameter If the method does not return a value we use the void Java keyword.

Can a method not return anything?

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.

Why is my method not returning a value JAVA?

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.

Does method end after return statement Java?

Yes, it will end the method once a value is returned.


1 Answers

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.

like image 159
Louis Wasserman Avatar answered Nov 15 '22 22:11

Louis Wasserman