嵌套的try-终于在C# [英] Nested try-finally in C#

查看:114
本文介绍了嵌套的try-终于在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不是行Console.WriteLine(ASDF);执行?所有的人都。应该不是也像我们不能从最终范围跳出?



 静态布尔Func键()
{

{

{
}
终于
{

{
抛出新ApplicationException的();
}
终于
{
Console.WriteLine(ASD);
}

Console.WriteLine(ASDF);
}
}
终于
{
Console.WriteLine(ASD);
}
}


解决方案

最后块的唯一保证(至少大部分保证,除非看到从下面MSDN),他们将进入在try块抛出异常的事件。如果你抛出一个异常 finally块,异常会导致控制离开finally块和finally块将不执行中的代码的其余部分。


$内b $ b

在你的情况,也就是没有被执行线路在同一finally块异常后发生的,所以它被跳过。



MSDN - 尝试,终于的:



<块引用>

最后块清理是在的任何资源有用>尝试块,并运行任何代码,即使在尝试块发生异常必须执行
。通常情况下,控制离开时的最后
语句执行尝试
语句,控制转移是否发生是由于$的结果b $ b标准执行,一个破发执行 继续 转到收益
声明或异常出的传播尝试语句。



在一个处理的异常时,相关的最后块保证
中运行。但是,如果异常未处理时,
的执行最后块是依赖于异常是如何放松操作
触发。这反过来,是依赖于您的计算机是如何设置的。
有关更多信息,请参阅CLR未处理的异常处理。



Why isn't the line "Console.WriteLine("asdf");" executed? All the others are. Shouldn't it also be as we can't jump out from the finally scope?

static bool Func()
{
    try
    {
        try
        {
        }
        finally
        {
            try
            {
                throw new ApplicationException();
            }
            finally
            {
                Console.WriteLine("asd");
            }

            Console.WriteLine("asdf");
        }
    }
    finally
    {
        Console.WriteLine("asd");
    }
}

解决方案

Finally blocks only guarantee (at least mostly guarantee, see except from MSDN below) that they will be entered in the event that the try block throws an exception. If you throw an exception within the finally block, the exception will cause control to leave the finally block and the rest of the code within that finally block will not execute.

In your case, the line that isn't being executed is occurring after an exception in the same finally block, so it gets skipped.

From MSDN - try-finally:

The finally block is useful for cleaning up any resources that are allocated in the try block, and for running any code that must execute even if an exception occurs in the try block. Typically, the statements of a finally block are executed when control leaves a try statement, whether the transfer of control occurs as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.

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.

这篇关于嵌套的try-终于在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆