正确使用RuntimeException? [英] Proper use of RuntimeException?
问题描述
什么时候应该从 RuntimeException
而不是异常
?
When should I derive an exception from RuntimeException
instead of Exception
?
A RuntimeException
不必在方法的 throws
子句中声明,这可能是 ,因为它不必具体列出或 ,因为明确声明方法异常是个好习惯。
A RuntimeException
does not have to be declared in a method's throws
clause, which may be good since it doesn't have to specifically listed or bad because it is good practice to explicitly declare a method's exception.
想法?
推荐答案
如果客户可以合理预期
恢复从异常,使它
a检查异常。如果客户端
无法从
异常中进行任何恢复,请将其作为未经检查的
异常。
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
请注意,未检查的异常来自 RuntimeException
,被检查的异常是从 异常
。
Note that an unchecked exception is one derived from RuntimeException
and a checked exception is one derived from Exception
.
为什么抛出一个 RuntimeException
如果客户端无法从异常中恢复任何东西?文章解释:
Why throw a RuntimeException
if a client cannot do anything to recover from the exception? The article explains:
运行时异常表示
的问题是
编程问题的结果,因此,API客户端
代码不能合理地预期到
从他们中恢复或以
方式处理它们。这些问题包括
算术异常,如
除以零;指针异常,
,如尝试通过空引用访问对象
;并索引
异常,例如尝试
通过太大或太小的
索引访问数组元素。
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.
这篇关于正确使用RuntimeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!