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

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

问题描述

是否可以确定代码是否正在执行在 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.

实际上,这显然是在此处。有可能以非常黑客的方式进行检测。我不会真的使用这种技术,但有趣的是知道这是可能的。

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天全站免登陆