Error 和 Exception的区别

错误和异常的区别(Error vs Exception) 
今天面试问了这样一个问题,"Error" 和 "Exception"之间有啥区别?我以为挺有意思,可是彷佛又不能脱口而出。查找了一番资料以后,稍微总结了一下。
1)  error都是继承自父类java.lang.Error,而exception都继承自java.lang.Exception.java

2)  再看看JDK中对于java.lang.Error和java.lang.Exception的解释。
    java.lang.Error: An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. 即:Error是Throwable的子类,用于标记严重错误。合理的应用程序不该该去try/catch这种错误。绝大多数的错误都是非正常的,就根本不应出现的。     java.lang.Exception: The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. 即Exception 是Throwable的一种形式的子类,用于指示一种合理的程序想去catch的条件。即它仅仅是一种程序运行条件,而非严重错误,而且鼓励用户程序去catch它。

3)  Error和RuntimeException 及其子类都是未检查的异常(unchecked exceptions),而全部其余的Exception类都是检查了的异常(checked exceptions).
checked exceptions: 一般是从一个能够恢复的程序中抛出来的,而且最好可以从这种异常中使用程序恢复。好比FileNotFoundException, ParseException等。
unchecked exceptions: 一般是若是一切正常的话本不应发生的异常,可是的确发生了。好比ArrayIndexOutOfBoundException, ClassCastException等。从语言自己的角度讲,程序不应去catch这类异常,虽然可以从诸如RuntimeException这样的异常中catch并恢复,可是并不鼓励终端程序员这么作,由于彻底没要必要。由于这类错误自己就是bug,应该被修复,出现此类错误时程序就应该当即中止执行。 所以,面对Errors和unchecked exceptions应该让程序自动终止执行,程序员不应作诸如try/catch这样的事情,而是应该查明缘由,修改代码逻辑。程序员

相关文章
相关标签/搜索