Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any standard annotation to indicate nothrow semantics in Java?

I'd like to document an interface method in Java as not being allowed to propagate exceptions and have some sort of static analysis verifying that implementations of this method catch and handle any exceptions that may have propagated to it. Something along the lines of @NoThrow.

For example, I'd like to be able to write:

interface SomeServiceProviderInterface {
   @NoThrow
   @NonNull
   SomeResult someComputation();
}

... and have some guarantee that implementations obey this interface contract. Is there an annotation and static analysis tool that already does this? If not, does anyone know if this is achievable with an annotation processor (can it see whether the code includes a try...catch block?) and/or have any pointers or advice on how to go about implementing such a thing? Thanks!

like image 730
Michael Aaron Safyan Avatar asked Sep 03 '15 01:09

Michael Aaron Safyan


2 Answers

There can be no such annotation, because it is impossible to guarantee that a method does not throw exceptions. This is because any method may throw a VirtualMachineError at anytime. In particular, a method could throw an OutOfMemoryError even if it does not directly or indirectly allocate memory itself (using a new operator). This is not a merely theoretical concern: some concurrent garbage collectors will do this if a garbage collection thread takes too long.

like image 185
Raedwald Avatar answered Oct 22 '22 03:10

Raedwald


An unsatisfactory answer

Exceptions are a valuable language element, they not only allow you to handle errors but also to shortcut a computation. Imagine you are searching for the shortest list in a highly branching recursive algorithm. When happening upon an empty list, you could immediately return a result by throwing an exception, signalling that an empty list was found.

And of course to skip a computation that is not feasible instead of bubbling up nulls is subroutines.

So this matter is on the level of avoiding many if-statements to facilitate testing (as otherwise untested code sections may be buried in the code's control flow).

Much effort would be class scanning for importing exception classes, and dangerous calls (Integer.parseInt). Some of that, code analyzers already warn against.

I assume that try {...} catch (Throwable/RuntimeException e) {} is just for some legacy cases. There AOP would help too.

The best alternative would be to integrate exceptions. There are evaluation libraries (I do not remember their names - maybe relating to continuations) that can handle exceptions and process mixed results. A bit like what Streams are doing now, where exceptions are handled partly asynchronously and such.

like image 20
Joop Eggen Avatar answered Oct 22 '22 03:10

Joop Eggen