在 .NET 中处理和引发异常Handling and throwing exceptions in .NET

应用程序必须能够以一致的方式处理执行期间发生的错误。Applications must be able to handle errors that occur during execution in a consistent manner. .NET 提供一种以统一方式向应用程序报错的模型:.NET 操作通过引发异常来指示故障。.NET provides a model for notifying applications of errors in a uniform way: .NET operations indicate failure by throwing exceptions.

异常Exceptions

异常是执行程序遇到的所有错误条件或意外行为。An exception is any error condition or unexpected behavior that is encountered by an executing program. 异常可能由你的代码或调用的代码(如共享库)中的错误、不可用的操作系统资源、运行时遇到的意外情况(如无法验证的代码)等引发。Exceptions can be thrown because of a fault in your code or in code that you call (such as a shared library), unavailable operating system resources, unexpected conditions that the runtime encounters (such as code that can't be verified), and so on. 应用程序可从这些情况中的一些中恢复,但无法从其他情况中恢复。Your application can recover from some of these conditions, but not from others. 尽管可以从大多数应用程序异常中恢复,但不能从大多数运行时异常中恢复。Although you can recover from most application exceptions, you can't recover from most runtime exceptions.

在 .NET中,异常是从 System.Exception 类继承的对象。In .NET, an exception is an object that inherits from the System.Exception class. 异常引发自发生问题的代码区域。An exception is thrown from an area of code where a problem has occurred. 异常在堆栈中向上传递,直到应用程序对其进行处理或者程序终止。The exception is passed up the stack until the application handles it or the program terminates.

异常与传统的错误处理方法Exceptions vs. traditional error-handling methods

传统上,语言的错误处理模型依赖语言检测错误和针对错误查找其处理程序的独特方式,或者依赖操作系统提供的错误处理机制。Traditionally, a language's error-handling model relied on either the language's unique way of detecting errors and locating handlers for them, or on the error-handling mechanism provided by the operating system. .NET 实现异常处理的方式有以下优点:The way .NET implements exception handling provides the following advantages:

  • 引发和处理异常的方式与 .NET 编程语言的相同。Exception throwing and handling works the same for .NET programming languages.

  • 处理异常不需要任何特定的语言语法,但允许每种语言定义自己的语法。Doesn't require any particular language syntax for handling exceptions, but allows each language to define its own syntax.

  • 可跨进程,甚至跨计算机边界引发异常。Exceptions can be thrown across process and even machine boundaries.

  • 可向应用程序添加异常处理代码以提高程序的可靠性。Exception-handling code can be added to an application to increase program reliability.

异常相较于其他错误通知方法(如返回代码)具有多种优势。Exceptions offer advantages over other methods of error notification, such as return codes. 故障不会被忽略掉,因为如果引发了异常且未得到解决,运行时会终止应用程序。Failures don't go unnoticed because if an exception is thrown and you don't handle it, the runtime terminates your application. 因为代码未能检查出是否存在故障返回代码,所以无效值不会继续在系统中传播。Invalid values don't continue to propagate through the system as a result of code that fails to check for a failure return code.

常见异常Common exceptions

下表列出了一些常见的异常,以及会引发这些异常的原因的示例。The following table lists some common exceptions with examples of what can cause them.

异常类型Exception type 说明Description 示例Example
Exception 所有异常的基类。Base class for all exceptions. 无(使用此异常的派生类)。None (use a derived class of this exception).
IndexOutOfRangeException 仅当错误地对数组进行索引时,才由运行时引发。Thrown by the runtime only when an array is indexed improperly. 在数组的有效范围外对数组进行索引:Indexing an array outside its valid range:
arr[arr.Length+1]
NullReferenceException 仅当引用 null 对象时,才由运行时引发。Thrown by the runtime only when a null object is referenced. object o = null;
o.ToString();
InvalidOperationException 当处于无效状态时,由方法引发。Thrown by methods when in an invalid state. 从基础集合删除项后调用 Enumerator.MoveNext()Calling Enumerator.MoveNext() after removing an item from the underlying collection.
ArgumentException 所有自变量异常的基类。Base class for all argument exceptions. 无(使用此异常的派生类)。None (use a derived class of this exception).
ArgumentNullException 由不允许参数为 null 的方法引发。Thrown by methods that do not allow an argument to be null. String s = null;
"Calculate".IndexOf(s);
ArgumentOutOfRangeException 由验证自变量是否位于给定范围内的方法引发。Thrown by methods that verify that arguments are in a given range. String s = "string";
s.Substring(s.Length+1);

请参阅See also