zoukankan      html  css  js  c++  java
  • 错误和异常的区别(Error vs Exception)

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

    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这样的事情,而是应该查明原因,修改代码逻辑。

  • 相关阅读:
    《分布式系统关注点——数据一致性(上篇)》阅读笔记
    2.23寒假学习记录
    2.22寒假学习记录
    2.21寒假学习记录
    2.20寒假学习记录
    2.19寒假学习记录
    2.18寒假学习记录
    2.17寒假学习记录
    2.17周一毕设改进计划
    2.16寒假学习记录
  • 原文地址:https://www.cnblogs.com/anthony0859/p/3915333.html
Copyright © 2011-2022 走看看