c# – 在catch和最后抛出异常. CLR行为与try-catch块

参见英文答案 > When is finally run if you throw an exception from the catch block?                                    7个
我写了简单的C#控制台应用程序:

class Mystery
{
    static void Main(string[] args)
    {
        MakeMess();
    }

    private static void MakeMess()
    {
        try
        {
            System.Console.WriteLine("try");
            throw new Exception(); // let's invoke catch
        }
        catch(Exception)
        {
            System.Console.WriteLine("catch");
            throw new Exception("A");
        }
        finally
        {
            System.Console.WriteLine("finally");
            throw new Exception("B");
        }
    }
}

控制台中给出的输出是:

try

catch

Unhandled Exception: System.Exception: A at Mystery.Program.MakeMess() in …

似乎CLR捕获了A,并且根本没有调用finally块.

但是当我用try-catch块包围对MakeMess()的调用时:

static void Main(string[] args)
{
    try
    {
        MakeMess();
    }
    catch(Exception ex)
    {
        System.Console.WriteLine("Main caught " + ex.Message);
    }
}

输出看起来完全不同:

try

catch

finally

Main caught B

当在方法之外严格处理Exception时,似乎从MakeMess()传播的Exception是不同的.

这种行为有什么解释?

解决方法:

您所看到的行为与最终阻止投掷无关.你只是在你的应用程序中有一个未处理的异常,当发生这种情况时,所有的赌注都会被关闭,包括最后的块是否运行:

MSDN文档:

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up. For more information, see Unhandled Exception Processing in the CLR.

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

如果finally块必须运行,那么解决方案就是准确地完成你在第二个片段中所做的事情:处理未处理的异常.

上一篇:c# – 终结者线程ID


下一篇:.NET Framework 简介