c# - 判断是否因为抛出异常而执行到 finally block 中

标签 c# exception idisposable finally try-catch

是否有可能确定代码当前是否由于抛出异常而在 finally 处理程序的上下文中执行?我更喜欢使用 IDisposable 模式来实现进入/退出范围功能,但对这种模式的一个担忧是,如果出现异常,您可能不一定希望发生范围结束行为出现在 using 的正文中。我会寻找这样的东西:

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();
    }
}

我还有其他方法可以完成此操作(将委托(delegate)传递给围绕具有特定行为的调用的函数),但我很好奇是否可以使用 IDisposable 模式来完成此操作。


实际上,这显然在 here 之前已经被询问和回答过.有可能以一种非常骇人听闻的方式进行检测。我实际上不会使用该技术,但很有趣的是知道它是可能的。

最佳答案

我看到的实现这个的方法需要一个额外的方法:

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 )。

关于c# - 判断是否因为抛出异常而执行到 finally block 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3301507/

相关文章:

c# - 为什么要用 using 语句初始化对话框?

c# - 为什么我的客户端得到 "System.Uri cannot be serialized because it does not have a parameterless constructor."?

c# - 数学表达式解析器中的右结合运算符

python - python 中的回溯对象

java - 我的国际象棋程序的线程 "main"java.lang.NullPointerException 中出现异常

c# - 安全返回构造的 IDisposables 的最佳方法是什么?

c# - 实现 IDisposable 的类可以是托管资源吗?

c# - WIX 自定义操作调试不起作用

c# - 将 EF CodeFirst 基类转换为继承类(使用 table-per-type)

java - 数组类的空指针异常