异常和异常处理(C# 编程指南)Exceptions and Exception Handling (C# Programming Guide)

C# 语言的异常处理功能有助于处理在程序运行期间发生的任何意外或异常情况。The C# language's exception handling features help you deal with any unexpected or exceptional situations that occur when a program is running. 异常处理功能使用 trycatchfinally 关键字来尝试执行可能失败的操作、在你确定合理的情况下处理故障,以及在事后清除资源。Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to handle failures when you decide that it is reasonable to do so, and to clean up resources afterward. 公共语言运行时 (CLR)、.NET Framework/任何第三方库或应用程序代码都可以生成异常。Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any third-party libraries, or by application code. 异常是使用 throw 关键字创建而成。Exceptions are created by using the throw keyword.

在许多情况下,异常并不是由代码直接调用的方法抛出,而是由调用堆栈中再往下的另一方法抛出。In many cases, an exception may be thrown not by a method that your code has called directly, but by another method further down in the call stack. 如果出现这种情况,CLR 会展开堆栈,同时针对特定异常类型查找包含 catch 代码块的方法,并执行找到的首个此类 catch 代码块。When this happens, the CLR will unwind the stack, looking for a method with a catch block for the specific exception type, and it will execute the first such catch block that if finds. 如果在调用堆栈中找不到相应的 catch 代码块,将会终止进程并向用户显示消息。If it finds no appropriate catch block anywhere in the call stack, it will terminate the process and display a message to the user.

在以下示例中,方法用于测试除数是否为零,并捕获相应的错误。In this example, a method tests for division by zero and catches the error. 如果没有异常处理功能,此程序将终止,并显示 DivideByZeroException was unhandled 错误。Without the exception handling, this program would terminate with a DivideByZeroException was unhandled error.

class ExceptionTest
{
    static double SafeDivision(double x, double y)
    {
        if (y == 0)
            throw new System.DivideByZeroException();
        return x / y;
    }
    static void Main()
    {
        // Input for test purposes. Change the values to see
        // exception handling behavior.
        double a = 98, b = 0;
        double result = 0;

        try
        {
            result = SafeDivision(a, b);
            Console.WriteLine("{0} divided by {1} = {2}", a, b, result);
        }
        catch (DivideByZeroException e)
        {
            Console.WriteLine("Attempted divide by zero.");
        }
    }
}

异常概述Exceptions Overview

异常具有以下属性:Exceptions have the following properties:

  • 异常是最终全都派生自 System.Exception 的类型。Exceptions are types that all ultimately derive from System.Exception.

  • 在可能抛出异常的语句周围使用 try 代码块。Use a try block around the statements that might throw exceptions.

  • try 代码块中出现异常后,控制流会跳转到调用堆栈中任意位置上的首个相关异常处理程序。Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. 在 C# 中,catch 关键字用于定义异常处理程序。In C#, the catch keyword is used to define an exception handler.

  • 如果给定的异常没有对应的异常处理程序,那么程序会停止执行,并显示错误消息。If no exception handler for a given exception is present, the program stops executing with an error message.

  • 除非可以处理异常并让应用程序一直处于已知状态,否则不捕获异常。Do not catch an exception unless you can handle it and leave the application in a known state. 如果捕获 System.Exception,使用 catch 代码块末尾的 throw 关键字重新抛出异常。If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block.

  • 如果 catch 代码块定义异常变量,可以用它来详细了解所发生的异常类型。If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred.

  • 使用 throw 关键字,程序可以显式生成异常。Exceptions can be explicitly generated by a program by using the throw keyword.

  • 异常对象包含错误详细信息,如调用堆栈的状态和错误的文本说明。Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.

  • 即使有异常抛出,finally 代码块中的代码仍会执行。Code in a finally block is executed even if an exception is thrown. 使用 finally 代码块可释放资源。例如,关闭在 try 代码块中打开的任何流或文件。Use a finally block to release resources, for example to close any streams or files that were opened in the try block.

  • .NET Framework 中的托管异常在 Win32 结构化异常处理机制的基础之上实现。Managed exceptions in the .NET Framework are implemented on top of the Win32 structured exception handling mechanism. 有关详细信息,请参阅结构化异常处理 (C/C++)速成教程:深入了解 Win32 结构化异常处理For more information, see Structured Exception Handling (C/C++) and A Crash Course on the Depths of Win32 Structured Exception Handling.

若要详细了解异常和异常处理,请参阅以下主题:See the following topics for more information about exceptions and exception handling:

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范中的异常For more information, see Exceptions in the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See Also