如何确定是否正在处理.NET异常? [英] How to determine whether a .NET exception is being handled?

查看:131
本文介绍了如何确定是否正在处理.NET异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在调查C#中的编码模式,其中我们希望使用一个特殊类的using子句,其中 Dispose()方法不同事情取决于使用的身体是否正常退出或有异常。



为了我的最大的了解,CLR跟踪当前正在处理的异常,直到它被catch处理程序消耗。然而,这些信息是否以任何方式暴露于代码访问中并不完全清楚。你知道是否是,如果是,如何访问它?



例如:

  using(var x = new MyObject())
{
x.DoSomething();
x.DoMoreThings();


class MyObject:IDisposable
{
public void Dispose()
{
if(ExceptionIsBeingHandled)
回滚);
else
Commit();
}
}

这看起来几乎像系统.Transactions.TransactionScope ,除了成功/失败不是通过调用 x.Complete()确定,而是基于使用正文正常退出。

解决方案

http:/ /www.codewrecks.com/blog/index.php/2008/07/25/detecting-if-finally-block-is-executing-for-an-manhandled-exception/ 描述了一个黑客来检测如果您的代码在异常处理模式下执行。它使用 Marshal.GetExceptionPointers 以查看异常是否为活动。



但请记住:

注释



GetExceptionPointers用于编译器支持结构化异常处理SEH)。
注意:



此方法使用SecurityAction.LinkDemand阻止它被不受信任的代码调用;只有立即调用者需要具有SecurityPermissionAttribute.UnmanagedCode权限。如果您的代码可以从部分受信任的代码调用,请勿将用户输入传递给Marshal类方法而不进行验证。对于使用LinkDemand成员的重要限制,请参阅Demand vs. LinkDemand。


We're investigating a coding pattern in C# in which we'd like to use a "using" clause with a special class, whose Dispose() method does different things depending on whether the "using" body was exited normally or with an exception.

To the best of my understanding, the CLR keeps track of the current exception being handled until it's been consumed by a "catch" handler. However it's not entirely clear whether this information is exposed in any way for the code to access. Do you know whether it is, and if so, how to access it?

For example:

using (var x = new MyObject())
{
    x.DoSomething();
    x.DoMoreThings();
}

class MyObject : IDisposable
{
    public void Dispose()
    {
        if (ExceptionIsBeingHandled)
            Rollback();
        else
            Commit();
    }
}

This looks almost like System.Transactions.TransactionScope, except that success/failure is not determined by a call to x.Complete(), but rather based on whether the using body was exited normally.

解决方案

http://www.codewrecks.com/blog/index.php/2008/07/25/detecting-if-finally-block-is-executing-for-an-manhandled-exception/ describes a "hack" to detect if your code is executed in exception handling mode or not. It uses Marshal.GetExceptionPointers to see if an exception is "active".

But keep in mind:

Remarks

GetExceptionPointers is exposed for compiler support of structured exception handling (SEH) only. NoteNote:

This method uses SecurityAction.LinkDemand to prevent it from being called from untrusted code; only the immediate caller is required to have SecurityPermissionAttribute.UnmanagedCode permission. If your code can be called from partially trusted code, do not pass user input to Marshal class methods without validation. For important limitations on using the LinkDemand member, see Demand vs. LinkDemand.

这篇关于如何确定是否正在处理.NET异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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