try-finally(C# 参考)

使用 finally 块,可以清理在 Try 中分配的任何资源,而且,即使在 try 块中发生异常,您也可以运行代码。 通常,控件离开 try 语句之后,finally 的语句会阻止运行。 正常执行中 breakcontinuegotoreturn 语句的执行,或对 try 语句外部异常的传播,可能会导致发生控件转换。

已处理的异常中会确保运行关联的 finally 块。 但是,如果异常未得到处理,则 finally 块的执行取决于如何触发异常展开操作。 此操作又取决于计算机是如何设置的。 有关更多信息,请参见 Unhandled Exception Processing in the CLR(CLR 中的未经处理的异常处理)。

通常,当未经处理的异常中止应用程序时,finally 块是否运行并不重要。 但是,如果您拥有的 finally 块中的语句必须在该环境下运行,则一个解决方案是将 catch 块添加到 try-finally 语句中。 或者,可以捕获可能是在调用堆栈更上方的 try-finally 语句的 try 块中引发的异常。 即可以捕获调用了包含 try-finally 语句的方法中的、或调用了该方法的方法中的、或调用堆栈中任何方法中的异常。 如果未捕获异常,则 finally 块的执行取决于操作系统是否选择触发异常展开操作。

示例

在下面的示例中,无效转换语句导致 System.InvalidCastException 异常。 异常未处理。

public class ThrowTestA
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // To run the program in Visual Studio, type CTRL+F5\. Then 
            // click Cancel in the error dialog.
            Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
                "error depends on how the exception unwind operation is triggered.");
            Console.WriteLine("i = {0}", i);
        }
    }
    // Output:
    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
    //
    // Execution of the finally block after an unhandled
    // error depends on how the exception unwind operation is triggered.
    // i = 123
}

在下面的示例中,TryCast 方法中的异常在延伸调用堆栈的方法中被捕获。

public class ThrowTestB
{
    static void Main()
    {
        try
        {
            // TryCast produces an unhandled exception.
            TryCast();
        }
        catch (Exception ex)
        {
            // Catch the exception that is unhandled in TryCast.
            Console.WriteLine
                ("Catching the {0} exception triggers the finally block.",
                ex.GetType());

            // Restore the original unhandled exception. You might not
            // know what exception to expect, or how to handle it, so pass 
            // it on.
            throw;
        }
    }

    public static void TryCast()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // Report that the finally block is run, and show that the value of
            // i has not been changed.
            Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
        }
    }
    // Output:
    // In the finally block in TryCast, i = 123.

    // Catching the System.InvalidCastException exception triggers the finally block.

    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}

有关 finally 的更多信息,请参见 try-catch-finally

C# 还包含使用语句,该语句可为 IDisposable 对象提供类似功能的方法语法。

C# 语言规范

有关详细信息,请参阅 C# 语言规范。该语言规范是 C# 语法和用法的权威资料。

请参阅

C# 参考

C# 编程指南

C# 关键字

try、throw 和 catch 语句 (C++)

异常处理语句(C# 参考)

throw(C# 参考)

try-catch(C# 参考)

如何:显式引发异常