java - 是否必须处理运行时异常?

标签 java exception

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.

ExceptionError 都扩展了 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/

相关文章:

java - 更改 JTabbedPane 的外观

java - 为 JFileChooser 上的选定文件设置自己的文件图标

java - 替代计划的任务,将来可能会取消

oracle - Oracle 的 ora-XXXX 异常报告方式是什么?

java - 对空结果集的非法操作

c++ - 有没有办法在 MSVC 输出中禁用 ".pdata"/"ExceptionDir"和 "UNWIND_INFO"?

java - 在 Java 包上使用 "ls"命令时出现不支持的方案错误

java - 如何以编程方式使用 Maven 下载 jar

java - 服务验证: throw an exception if validation failed

exception - Ajax :ModalPopup js exception,BackgroundCssClass 为空