确定是否在执行finally块由于被抛出的异常 [英] Determine if executing in finally block due to exception being thrown

查看:167
本文介绍了确定是否在执行finally块由于被抛出的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以确定代码是在最后处理程序异常的结果的情况下被抛出当前执行的?我相当喜欢使用的IDisposable 模式来实现进入/退出作用域的功能,但这种模式的一个问题是,你不一定想要结束范围如果在的身体发生异常使用发生的行为。我会找这样的事:

Is it possible to determine if code is currently executing in the context of a finally handler as a result of an exception being thrown? I'm rather fond of using the IDisposable pattern to implement entry/exit scoping functionality, but one concern with this pattern is that you might not necessarily want the end-of-scope behavior to occur if an exception occurs in the body of the using. I'd be looking for something like this:

public static class MyClass
{
    public static void MyMethod()
    {
        using (var scope = MyScopedBehavior.Begin())
        {
            //Do stuff with scope here
        }
    }
}

public sealed class MyScopedBehavior : IDisposable
{
    private MyScopedBehavior()
    {
        //Start of scope behavior
    }

    public void Dispose()
    {
        //I only want to execute the following if we're not unwinding
        //through finally due to an exception:
        //...End of scope behavior    
    }

    public static MyScopedBehavior Begin()
    {
        return new MyScopedBehavior();
    }
}

有其他的方式,我可以做到这一点(传递授人以围绕与特定行为的调用)函数,但我很好奇,如果有可能使用的IDisposable 模式来做到这一点。

There are other ways I can accomplish this (pass a delegate to a function that surrounds the call with particular behavior), but I'm curious if it's possible to do it using the IDisposable pattern.

其实,这显然已经问及的此处。这有可能在一个非常hackish的那种方式来检测。我不会真的使用该技术,但它也同样吸引知道这是可能的。

Actually, this has apparently been asked and answered before here. It's possible to detect in a very hackish sort of way. I wouldn't actually use that technique, but it's interesting to know that it's possible.

推荐答案

实现这一点,手段我见过需要一个额外的方法:

The means of accomplishing this that I've seen require an extra method:

public static void MyMethod()
{
    using (var scope = MyScopedBehavior.Begin())
    {
        //Do stuff with scope here
        scope.Complete(); // Tells the scope that it's good
    }
}



通过这样的范围,你的范围对象可以追踪无论是处理因错误或成功运作。这是的TransactionScope 拍摄,例如方法(见的TransactionScope.Complete )。

By doing this, your scope object can track whether it's disposing because of an error, or a successful operation. This is the approach taken by TransactionScope, for example (see TransactionScope.Complete).

这篇关于确定是否在执行finally块由于被抛出的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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