在C#中,我怎样才能重新抛出的InnerException又不失堆栈跟踪?堆栈、又不、抛出、InnerException

2023-09-02 11:44:54 作者:失意的片刻

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

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

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

解决方案

在 .NET 4.5 现在出现的ExceptionDispatchInfo类。

java中如何抛出异常使程序不中断 7

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

 尝试
{
    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.