未检查异常或运行时异常之间的差异 [英] Difference between Unchecked exception or runtime exception

查看:152
本文介绍了未检查异常或运行时异常之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个采访问题。未检查的异常和错误之间的主要区别是什么?他们将终止程序。

解决方案

如其名称所述,未选中的异常没有在编译时检查,这意味着编译器不需要捕获或指定(使用 throws )的方法。属于此类别的课程详见:


错误是一个单独的
子类 Throwable ,不同于类层次结构中的
异常
允许程序使用成语:

 } catch(异常e){
pre>

捕获从
恢复可能没有
捕获错误的所有异常,恢复是
通常不可能。 / p>

总而言之, RuntimeException 未检查异常的一个子集对于可以进行恢复的异常(但未检查的异常不是 RuntimeException 的同义词,许多人在此处回答)。


This was an interview question. What is the main difference between unchecked exception and error as both are not caught? They will terminate the program.

解决方案

As stated by their name, unchecked exceptions are not checked at compile-time which means that the compiler doesn't require methods to catch or to specify (with a throws) them. Classes belonging to this category are detailed in the section 11.2 Compile-Time Checking of Exceptions of the JLS:

The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers. See §11.5 for a description of the exception class hierarchy and some of the exception classes defined by the Java API and Java virtual machine.

The following picture illustrates the Exception hierarchy:

The class Error and its subclasses are exceptions from which ordinary programs are not ordinarily expected to recover and, as explained in 11.5 The Exception Hierarchy:

The class Error is a separate subclass of Throwable, distinct from Exception in the class hierarchy, to allow programs to use the idiom:

} catch (Exception e) {

to catch all exceptions from which recovery may be possible without catching errors from which recovery is typically not possible.

To summarize, RuntimeException are a subset of unchecked exceptions for exceptions from which recovery is possible (but unchecked exception is not a synonym of RuntimeException as many are answering here).

这篇关于未检查异常或运行时异常之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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