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

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

问题描述

这是一道面试题.未经检查的异常和错误之间的主要区别是什么,因为两者都没有被捕获?他们将终止程序.

解决方案

正如他们的名字所说,unchecked exceptions not check at compile-time 这意味着编译器不需要方法来捕获或指定(使用 throws)它们.属于此类别的类在 :

<块引用>

Error 类是一个单独的Throwable 的子类,区别于Exception 在类层次结构中,以允许程序使用成语:

} 捕获(异常 e){

捕获所有异常没有恢复可能是可能的捕获从中恢复的错误通常是不可能的.

总而言之,RuntimeExceptionunchecked exceptions 的子集,用于可以从中恢复的异常(但 unchecked exception 不是 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天全站免登陆