关于java:抛出RuntimeException的方法是否应该在方法签名中指明它?

Should methods that throw RuntimeException indicate it in method signature?

例如,frameworks/jdk中的许多方法可能会抛出

但方法签名中没有指明这一点(因为这通常是为检查异常保留的实践)。我想说的是,在方法sigs中声明runtimeexceptions有很多好处(例如,类似于静态类型检查)。我是喝醉了还是别的?


我不会在签名中声明未经检查的异常,因为它会误导该API的用户。异常是否必须显式处理已不再明显。

在JavaDoc中声明它是一种更好的方法,因为它允许某人在认为有必要时处理它,但知道如果他们愿意,可以忽略它。这将清除选中和未选中之间的分隔。


从Oracle Java教程:

"If it's so good to document a method's API, including the exceptions
it can throw, why not specify runtime exceptions too?" Runtime
exceptions represent problems that are the result of a programming
problem, and as such, the API client code cannot reasonably be
expected to recover from them or to handle them in any way. Such
problems include arithmetic exceptions, such as dividing by zero;
pointer exceptions, such as trying to access an object through a null
reference; and indexing exceptions, such as attempting to access an
array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical
one they can be very numerous. Having to add runtime exceptions in
every method declaration would reduce a program's clarity.


看看JavaDoc for Collection添加

有一大堆未经检查的例外提到:

1
2
3
4
5
Throws:
UnsupportedOperationException - add is not supported by this collection.
ClassCastException - class of the specified element prevents it from being added to this collection.
NullPointerException - if the specified element is null and this collection does not support null elements.
IllegalArgumentException - some aspect of this element prevents it from being added to this collection.

如果你有耐心的话,我建议你用这种方式彻底记录下你的方法可能抛出的异常。在某种程度上,对未检查的异常执行此操作更为重要,因为检查的异常在某种程度上是自记录的(编译器强制调用代码确认它们)。


在我看来,至少在JavaDoc中为该方法声明运行时异常更好。在签名中声明它会使它更加明显地显示出当某些事情出错时可能发生的情况。这是我建议提供此信息的主要原因。

仅供参考:随着时间的推移(现在是2017年),我现在更倾向于只在JavaDoc中记录它们,并尽可能避免检查异常。


如果您编写的是供其他人使用的API,那么就有充分的理由在API中显式地记录您的意图,并且在方法签名中声明RuntimeExceptions也不会有不利的一面。


在我看来,不应在方法签名中声明未经检查的异常,因为这违背了它们的性质。

但是,如果一个方法可能会抛出一些未经检查的异常,注意到javadoc中@throws中可能出现的情况,那么对于其他调用该方法以了解可能发生的错误的方法会有所帮助。这只对调用者可能能够处理的异常(例如由于输入错误等导致的NPE)有用。


这与关于检查异常的讨论有关。大多数人都同意不应该在方法签名中声明异常。

还有一个关于如何使用运行时异常的讨论。我同意一个海报,运行时异常应该表示编程错误或致命条件。所以在签名中声明它们没有多大价值。每个方法都有可能通过一个。