是否有任何标准注释来指示 Java 中的 nothrow 语义? [英] Is there any standard annotation to indicate nothrow semantics in Java?

查看:30
本文介绍了是否有任何标准注释来指示 Java 中的 nothrow 语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想记录 Java 中的接口方法,因为它不允许传播异常,并进行某种静态分析来验证此方法的实现是否捕获并处理可能传播到它的任何异常.类似于 @NoThrow 的内容.

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.

例如,我希望能够写:

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

... 并保证实现遵守此接口契约.是否有注释和静态分析工具已经这样做了?如果没有,有没有人知道这是否可以通过注释处理器实现(它可以看到代码是否包含 try...catch 块?)和/或有关于如何实现这样的事情的任何指针或建议?谢谢!

... 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!

推荐答案

不能有这样的注解,因为无法保证一个方法不抛出异常.这是因为任何方法都可能随时抛出VirtualMachineError.特别是,一个方法可能会抛出 OutOfMemoryError 即使它本身没有直接或间接分配内存(使用 new 运算符).这不仅仅是理论上的问题:如果垃圾收集线程花费的时间太长,一些并发垃圾收集器会这样做.

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.

这篇关于是否有任何标准注释来指示 Java 中的 nothrow 语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆