Which statements are true?
<a>All classes of Exception extends Error.
<b>All classes of Error extends Exception.
<c>All Errors must be handled or declared.
<d>All classes of Exception extends Throwable.
<e>All Throwables must be handled or declared.
<f>All Exceptions must be handled or declared.
<g>Runtime Exceptions need never be handled or declared.
根据我的答案应该是 d 和 f,因为我认为需要处理运行时异常,例如算术异常,因为我们总是将它们放在 try 和 catch block 中,因此要处理它,但在“Kathy Sierra”的 ocjp 书中给出了它答案是 d 和 g。谁是正确的?我是否误解了什么?
最佳答案
a. All classes of Exception extends Error.
b. All classes of Error extends Exception.
d. All classes of Exception extends Throwable.
Exception
和 Error
都扩展了 Throwable
,因此 (a) 和 (b) 为 false,(d) 为 true。
c. All Errors must be handled or declared.
e. All Throwables must be handled or declared.
f. All Exceptions must be handled or declared.
以上均为虚假信息,请参阅此处:Java: checked vs unchecked exception explanation
g. Runtime Exceptions need never be handled or declared.
确实如此,原因与上面的链接相同。
这是一个未处理ArithmeticException
的简单示例(它扩展了RuntimeException
,它扩展了Exception
):
int a = 42 / 0; // that would only throw at runtime, no need to try..catch it
关于java - 是否必须处理运行时异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44031436/