在C#中,我怎样才能重新抛出的InnerException又不失堆栈跟踪? [英] In C#, how can I rethrow InnerException without losing stack trace?

查看:1001
本文介绍了在C#中,我怎样才能重新抛出的InnerException又不失堆栈跟踪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话,通过反射,这可能会导致异常的方法。我怎样才能通过例外手机号码没有包装的反射把它周围?我重新抛出的InnerException,但这会破坏堆栈跟踪。例如:code:

 公共无效的test1()
    {
        //抛出一个异常用于测试目的
        抛出新的ArgumentException(测试1);
    }

    无效的test2()
    {
        尝试
        {
            MethodInfo的MI = typeof运算(程序).GetMethod(测试1);
            mi.Invoke(本,NULL);
        }
        赶上(TargetInvocationException tiex)
        {
            //抛出新的异常
            扔tiex.InnerException;
        }
    }
 

解决方案

.NET 4.5 现在出现的<一个href="http://msdn.microsoft.com/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo.aspx"><$c$c>ExceptionDispatchInfo类。

这让您捕捉异常,并重新把它不改变堆栈跟踪:

 尝试
{
    task.Wait();
}
赶上(AggregateException前)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
 

这适用于任何异常,而不仅仅是 AggregateException

据介绍,由于等待 C#语言功能,它解开了内部异常,从 AggregateException 的事例,以使异步语言特性更像是同步的语言特点。

I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:

    public void test1()
    {
        // Throw an exception for testing purposes
        throw new ArgumentException("test1");
    }

    void test2()
    {
        try
        {
            MethodInfo mi = typeof(Program).GetMethod("test1");
            mi.Invoke(this, null);
        }
        catch (TargetInvocationException tiex)
        {
            // Throw the new exception
            throw tiex.InnerException;
        }
    }

解决方案

In .NET 4.5 there is now the ExceptionDispatchInfo class.

This lets you capture an exception and re-throw it without changing the stack-trace:

try
{
    task.Wait();
}
catch(AggregateException ex)
{
    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}

This works on any exception, not just AggregateException.

It was introduced due to the await C# language feature, which unwraps the inner exceptions from AggregateException instances in order to make the asynchronous language features more like the synchronous language features.

这篇关于在C#中,我怎样才能重新抛出的InnerException又不失堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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