# 异常处理

异常处理是一种编程语言机制，用于响应运行时错误：当执行过程中发生错误时，指令的正常流程被打断，控制权转移到指定的处理程序，该处理程序可以在当前例程中，也可以在调用它的某个例程中。Java 教程将异常定义为“程序执行期间发生、打断程序指令正常流程的事件”<sup>[1](https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html)</sup>，ISO/IEC TR 10176 将异常定义为程序功能不正确的实例，这类实例只能通过程序的执行动态确定；该定义区分了无法恢复的致命异常与非致命异常<sup>[2](https://www.iso.org/obp/ui?_escaped_fragment_=iso%3Astd%3Aiso-iec%3Atr%3A10176%3Aed-4%3Av1%3Aen)</sup>。

| 关键事实 | 详情 |
|---|---|
| 核心机制 | 错误会创建一个异常对象，该对象被抛出或引发；运行时在调用栈中搜索匹配的处理程序，逐帧展开，直到找到为止<sup>[1](https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html)</sup> |
| 典型语法 | `try` 块包围有风险的代码，`catch`/`except` 子句指明所处理的异常类型，`finally` 子句无论是否发生异常都会执行清理<sup>[3](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)</sup><sup> • </sup><sup>[4](https://docs.python.org/3/tutorial/errors.html)</sup> |
| 终止模型 | Python 使用终止模型：处理程序可以在外层继续执行，但无法修复错误原因并重试失败的操作，除非从头重新进入出错的代码<sup>[5](https://docs.python.org/3.11/reference/executionmodel.html)</sup> |
| 常见根类型 | 所有 C# 异常都派生自 `System.Exception`<sup>[3](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)</sup>；Python 的常见基类是 `BaseException`，其中 `Exception` 是非致命异常的基类<sup>[4](https://docs.python.org/3/tutorial/errors.html)</sup> |
| 受检与非受检 | Java 的受检异常必须由 try-catch 机制处理，或用 `throws` 子句声明；非受检异常，即 `RuntimeException` 及其子类，不在编译期检查<sup>[6](https://mpbou.edu.in/uploads/files/JAVA-f_merged.pdf)</sup> |
| 历史 | 异常处理由 PL/I 首创；Ada 在 PL/I 基础上取得重大进步，并且在 C++ 和 Java 出现之前，是唯一一种得到广泛使用且具备该特性的语言<sup>[7](https://ethw.org/Past_programming_languages_and_their_influences_on_today%27s_languages_and_programming_paradigms)</sup> |
| 无异常 | C 没有异常处理机制；其 API 通过错误码报告失败，这些错误码在运行时显现<sup>[8](https://discovery.ucl.ac.uk/10102129/1/kechagia_jss_18.pdf)</sup> |

## 机制如何运作

如果方法内部出现错误，该方法会构造一个对象并将其交给运行时系统；这个对象称为异常对象，携带有关错误的详细信息，例如错误类型以及错误发生时程序的状态。创建异常对象并将其交给运行时系统称为抛出异常<sup>[1](https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html)</sup>。随后，运行时系统搜索调用栈——即为了到达失败点而调用过的方法的有序列表——从发生错误的方法开始，按调用顺序反向进行。如果异常对象的类型与处理程序能够处理的类型匹配，则该处理程序被视为合适；如果搜索耗尽整个栈仍未找到，运行时系统以及程序便会终止<sup>[1](https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html)</sup>。

**处理程序的选择基于类型。** 在 C# 中，抛出异常时，运行时会寻找异常类型匹配的最近 `catch` 子句，依据被抛出异常的运行时类型判断：它先检查词法上包围当前方法的 `try` 语句，然后检查调用者的 `try` 语句，依此类推，直到遇到一个子句，其命名的类等于被抛出异常的类或是其基类。未命名异常类的 `catch` 子句可以处理任何异常<sup>[9](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/exceptions)</sup>。Python 的 `except` 子句工作方式相同：`except` 子句中的类匹配该类的实例或其派生类的实例所对应的异常，第一个匹配的子句会被触发，因此子句从具体到一般的排序很重要<sup>[4](https://docs.python.org/3/tutorial/errors.html)</sup>。

**无论结果如何都会执行清理。** `finally` 块中的代码无论是否抛出异常都会执行；通常用于释放资源，例如关闭在 `try` 块中打开的流或文件<sup>[3](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)</sup>。Python 还增加了一个可选的 `else` 子句，在 `try` 子句未引发任何异常时执行；以及 `with` 语句，将清理与对象的生命周期绑定，因此即使处理文件时遇到问题，文件也总会被关闭<sup>[4](https://docs.python.org/3/tutorial/errors.html)</sup>。

**处理与传播。** Ada 参考手册将处理异常出现（即响应异常事件）与传播异常（即不在当前上下文中响应它，从而在不同上下文中重新引发它）区分开来；一旦异常出现被引发，程序便放弃其正常执行流程，并将控制权交给合适的异常处理程序（如果存在的话）<sup>[10](https://www.adaic.org/resources/add_content/standards/05aarm/html/AA-11-4.html)</sup>。Ada 的 `raise` 语句引发一个具名异常，而处理程序内部的裸 `raise` 会重新引发导致控制转移到该处理程序的异常<sup>[11](https://www.govinfo.gov/content/pkg/GOVPUB-C13-ed09b1afe5945484042ab93e0b93a52e/pdf/GOVPUB-C13-ed09b1afe5945484042ab93e0b93a52e.pdf)</sup>。Python 用裸 `raise` 重新引发异常来支持同样的思路，并支持异常链：在 `except` 段内引发的未处理异常会附带正在处理的异常，而 `raise X from exc` 将一个异常标记为另一个异常的直接原因<sup>[4](https://docs.python.org/3/tutorial/errors.html)</sup>。C# 通过 `InnerException` 属性表达链式关系：该属性非空时，指向导致当前异常的异常；以这种方式链接在一起的异常对象数量可以任意多<sup>[9](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/exceptions)</sup>。

## 语言示例

**C# 与 .NET。** `try`、`catch` 和 `finally` 关键字支持 C# 的异常处理：它尝试执行可能失败的操作，在看起来合理的地方处理此类失败，然后释放涉及的资源。公共语言运行时（CLR）、.NET 或第三方库以及应用程序代码本身都可能产生异常，这些异常使用 `throw` 关键字抛出<sup>[3](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)</sup>。某些操作会自动抛出异常：如果分母为零，整数除法运算会抛出 `System.DivideByZeroException`<sup>[9](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/exceptions)</sup>。.NET 中的托管异常建立在 Win32 结构化异常处理机制之上<sup>[3](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)</sup>，并且 .NET 的模型对所有 .NET 编程语言都相同，同时允许每种语言定义自己的语法；异常可以跨进程甚至跨机器边界抛出<sup>[12](https://learn.microsoft.com/en-us/dotnet/standard/exceptions/index)</sup>。

**Python。** 解释器在检测到除零等运行时错误时会引发异常，程序则用 `raise` 语句显式引发异常；处理程序用 `try` … `except` 语句指定<sup>[5](https://docs.python.org/3.11/reference/executionmodel.html)</sup>。Python 中的错误处理遵循终止模型：处理程序可以了解出了什么问题并在更高层级恢复执行，但它无法修复底层问题并重新运行失败的操作；它唯一的选择是从头重新启动失败的代码。<sup>[5](https://docs.python.org/3.11/reference/executionmodel.html)</sup> 为了一次报告多个失败，例如在多个任务可能并行失败的并发框架中，内置的 `ExceptionGroup` 包装一个异常实例列表，使它们可以一起被引发，而 `except*` 只选择性地处理匹配某一类型的组成员<sup>[4](https://docs.python.org/3/tutorial/errors.html)</sup>。

**C++。** C++ 中的异常类似于 C# 和 Java 等语言中的异常；标准库异常类型 `invalid_argument` 定义在 `<stdexcept>` 头文件中，所有标准库函数都按值抛出未命名对象，其类型派生自 `std::exception`<sup>[13](https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/cpp/errors-and-exception-handling-modern-cpp.md)</sup><sup> • </sup><sup>[14](https://en.cppreference.com/cpp/language/exceptions)</sup>。C++ 实践定义了函数可以提供的三种异常保证：强保证、基本保证或无抛出（`noexcept`）保证<sup>[13](https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/cpp/errors-and-exception-handling-modern-cpp.md)</sup>。

**Java。** Java 的异常类分为受检异常和非受检异常。受检异常必须由 try-catch 机制处理，或在方法上添加 `throws` 声明；非受检异常包括 `RuntimeException`，是应用程序通常无法恢复的异常情况<sup>[6](https://mpbou.edu.in/uploads/files/JAVA-f_merged.pdf)</sup>。Java 的大部分异常处理特性取自 C++<sup>[15](https://www.researchgate.net/publication/281220362_Influences_on_the_design_of_exception_handling)</sup>。

## 历史

异常处理由 PL/I 语言首创，此后在大多数主流编程语言中流行起来，包括 Ada、ML、C++ 和 Java<sup>[16](https://www.sciencedirect.com/science/article/abs/pii/S0950584916300830)</sup>。在语言级机制出现之前，程序员依靠对过程返回错误码的正确文档说明来处理错误情形<sup>[15](https://www.researchgate.net/publication/281220362_Influences_on_the_design_of_exception_handling)</sup>。Ada 在异常处理方面相比 PL/I 有重大进步，并且在 C++ 和 Java 出现之前，是唯一一种得到广泛使用且具备该特性的语言<sup>[7](https://ethw.org/Past_programming_languages_and_their_influences_on_today%27s_languages_and_programming_paradigms)</sup>。

**CLU 的设计决策塑造了主流。** [芭芭拉·利斯科夫](https://www.edgepedia.org/zh/barbara-liskov)（Barbara Liskov）及其同事在 20 世纪 70 年代对 CLU 的研究，使异常成为每个过程签名的一部分，并采用了终止模型；终止模型成为主流语言采用的模型，包括 C++、Java 和 Python 在内的后续设计都遵循了它，而恢复模型则在很大程度上不再使用<sup>[17](https://www.cs.montana.edu/users/murphy/books/pl-design/eval/error-handling.html)</sup>。

## 实践与替代方案

相关指南将异常与断言区分开来：使用断言检查应始终为真或始终为假的条件，使用异常检查可能发生的错误，例如公共函数参数输入验证中的错误。异常适用于处理错误的代码与检测错误的代码之间隔着一个或多个中间函数调用的情况；在性能关键的循环中，或当处理与检测紧密耦合时，错误码可能更可取<sup>[13](https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/cpp/errors-and-exception-handling-modern-cpp.md)</sup>。C# 文档给出了类似建议：除非能够处理异常并使应用程序处于已知状态，否则不要捕获异常；如果捕获 `System.Exception`，请在 `catch` 块末尾使用 `throw` 关键字重新抛出它<sup>[3](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)</sup>。

编写正确的处理代码是一项公认的难点。一项有 119 名受试者参与的对照实验发现，使用可信性案例（dependability cases）——一种覆盖异常条件的结构化方法——对应着异常处理健壮性在统计上显著的 34% 提升（p < .01）<sup>[18](https://www.cs.cmu.edu/~bobski/pubs/tse00.html)</sup>。

异常的替代方案依然存在。C 的标准库和大多数操作系统调用通过返回码报告失败<sup>[17](https://www.cs.montana.edu/users/murphy/books/pl-design/eval/error-handling.html)</sup>，而 .NET 指出，异常相比返回码等其他错误通知方法具有优势，同时仍是若干选项之一<sup>[12](https://learn.microsoft.com/en-us/dotnet/standard/exceptions/index)</sup>。

## References

1. [What Is an Exception? The Java Tutorials, Oracle](https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html)
2. [ISO/IEC TR 10176:2003, Guidelines for the preparation of programming language standards, ISO](https://www.iso.org/obp/ui?_escaped_fragment_=iso%3Astd%3Aiso-iec%3Atr%3A10176%3Aed-4%3Av1%3Aen)
3. [Exceptions and Exception Handling, C# programming guide, Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/)
4. [8. Errors and Exceptions, Python 3 tutorial](https://docs.python.org/3/tutorial/errors.html)
5. [4. Execution model, Python 3.11 reference](https://docs.python.org/3.11/reference/executionmodel.html)
6. [Exception handling in Java (course text), mpbou.edu.in](https://mpbou.edu.in/uploads/files/JAVA-f_merged.pdf)
7. [Past programming languages and their influences on today's languages and programming paradigms, Engineering and Technology History Wiki](https://ethw.org/Past_programming_languages_and_their_influences_on_today%27s_languages_and_programming_paradigms)
8. [Exception handling in mobile apps, JSS paper via UCL Discovery](https://discovery.ucl.ac.uk/10102129/1/kechagia_jss_18.pdf)
9. [Exceptions, C# language specification, Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/exceptions)
10. [11.4 Exception Handling, Annotated Ada Reference Manual, Ada Resource Association](https://www.adaic.org/resources/add_content/standards/05aarm/html/AA-11-4.html)
11. [FIPS Pub: Reference manual for the Ada programming language (ANSI/MIL-STD-1815A), govinfo](https://www.govinfo.gov/content/pkg/GOVPUB-C13-ed09b1afe5945484042ab93e0b93a52e/pdf/GOVPUB-C13-ed09b1afe5945484042ab93e0b93a52e.pdf)
12. [Handling and throwing exceptions in .NET, Microsoft Learn](https://learn.microsoft.com/en-us/dotnet/standard/exceptions/index)
13. [Errors and exception handling, Modern C++, Microsoft cpp-docs](https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/cpp/errors-and-exception-handling-modern-cpp.md)
14. [Exceptions, cppreference.com](https://en.cppreference.com/cpp/language/exceptions)
15. [Influences on the design of exception handling, ResearchGate](https://www.researchgate.net/publication/281220362_Influences_on_the_design_of_exception_handling)
16. [A review on exception analysis, ScienceDirect](https://www.sciencedirect.com/science/article/abs/pii/S0950584916300830)
17. [Error handling, A Practical Introduction to Programming Language Design, Montana State University](https://www.cs.montana.edu/users/murphy/books/pl-design/eval/error-handling.html)
18. [Eliminating Exception Handling Errors with Dependability Cases, CMU](https://www.cs.cmu.edu/~bobski/pubs/tse00.html)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 25, 2026 · Edited: Sep 30, 2026; Oct 15, 2026; Oct 25, 2026 · Last review: Oct 25, 2026*

Topic: 社会与历史 › 语言与语言学 › 语言学 › Formal and computational linguistics › Concrete syntax of programming and query languages

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/exception-handling

English original: https://www.edgepedia.org/exception-handling
