---
title: "错误和异常的区别(Error vs Exception)"
author: "guibin"
date: "2011-08-22T14:00:48Z"
tags: []
categories: ["编程语言"]
slug: "error-vs-exception"
draft: false
lastmod: "2011-08-22T14:00:48Z"
id: 1154920
url: "https://guibin.iteye.com/blog/1154920"
---

错误和异常的区别(Error vs Exception)
guibin.beijing@gmail.com

今天突然有朋友问了这样一个问题，"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这样的事情，而是应该查明原因，修改代码逻辑。

参考资料：
<http://www.coderanch.com/t/269746/java-programmer-SCJP/certification/Error-vs-Exception>
<http://oss.org.cn/ossdocs/java/se/jdk6/docs/api/java/lang/Error.html>
<http://oss.org.cn/ossdocs/java/se/jdk6/docs/api/java/lang/Exception.html>