通过反射,我正在调用一个可能导致异常的方法。我怎样才能将异常传递给我的调用者而没有包装反射围绕它? 我重新抛出InnerException,但这破坏了堆栈跟踪。 示例代码:

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

当前回答

基于Paul turner的回答,我提出了一个扩展方法

    public static Exception Capture(this Exception ex)
    {
        ExceptionDispatchInfo.Capture(ex).Throw();
        return ex;
    }

返回ex. ist从未到达,但优点是我可以使用throw ex. capture()作为一行,这样编译器就不会引发一个不是所有代码路径返回值错误。

    public static object InvokeEx(this MethodInfo method, object obj, object[] parameters)
    {
        {
            return method.Invoke(obj, parameters);
        }
        catch (TargetInvocationException ex) when (ex.InnerException != null)
        {
            throw ex.InnerException.Capture();
        }
    }

其他回答

可以在不反射地重新抛出之前保留堆栈跟踪:

static void PreserveStackTrace (Exception e)
{
    var ctx = new StreamingContext  (StreamingContextStates.CrossAppDomain) ;
    var mgr = new ObjectManager     (null, ctx) ;
    var si  = new SerializationInfo (e.GetType (), new FormatterConverter ()) ;

    e.GetObjectData    (si, ctx)  ;
    mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData
    mgr.DoFixups       ()         ; // ObjectManager calls SetObjectData

    // voila, e is unmodified save for _remoteStackTraceString
}

与通过缓存委托调用InternalPreserveStackTrace相比,这浪费了大量的周期,但优点是只依赖于公共功能。下面是一些堆栈跟踪保存函数的常见使用模式:

// usage (A): cross-thread invoke, messaging, custom task schedulers etc.
catch (Exception e)
{
    PreserveStackTrace (e) ;

    // store exception to be re-thrown later,
    // possibly in a different thread
    operationResult.Exception = e ;
}

// usage (B): after calling MethodInfo.Invoke() and the like
catch (TargetInvocationException tiex)
{
    PreserveStackTrace (tiex.InnerException) ;

    // unwrap TargetInvocationException, so that typed catch clauses 
    // in library/3rd-party code can work correctly;
    // new stack trace is appended to existing one
    throw tiex.InnerException ;
}

在。net 4.5中现在有了ExceptionDispatchInfo类。

这可以让你捕获一个异常并重新抛出它而不改变堆栈跟踪:

using ExceptionDispatchInfo = 
    System.Runtime.ExceptionServices.ExceptionDispatchInfo;

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

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

它的引入是由于await c#语言特性,该特性从AggregateException实例中展开内部异常,以便使异步语言特性更像同步语言特性。

我认为你最好的办法就是把这个放在你的catch block里:

throw;

然后提取内部异常。

基于Paul turner的回答,我提出了一个扩展方法

    public static Exception Capture(this Exception ex)
    {
        ExceptionDispatchInfo.Capture(ex).Throw();
        return ex;
    }

返回ex. ist从未到达,但优点是我可以使用throw ex. capture()作为一行,这样编译器就不会引发一个不是所有代码路径返回值错误。

    public static object InvokeEx(this MethodInfo method, object obj, object[] parameters)
    {
        {
            return method.Invoke(obj, parameters);
        }
        catch (TargetInvocationException ex) when (ex.InnerException != null)
        {
            throw ex.InnerException.Capture();
        }
    }

没有人解释过ExceptionDispatchInfo之间的区别。Capture(ex). throw()和一个普通的throw,所以它在这里。

重新抛出捕获的异常的完整方法是使用ExceptionDispatchInfo。Capture(ex). throw()(仅在. net 4.5中可用)。

下面是测试这一点的必要情况:

1.

void CallingMethod()
{
    //try
    {
        throw new Exception( "TEST" );
    }
    //catch
    {
    //    throw;
    }
}

2.

void CallingMethod()
{
    try
    {
        throw new Exception( "TEST" );
    }
    catch( Exception ex )
    {
        ExceptionDispatchInfo.Capture( ex ).Throw();
        throw; // So the compiler doesn't complain about methods which don't either return or throw.
    }
}

3.

void CallingMethod()
{
    try
    {
        throw new Exception( "TEST" );
    }
    catch
    {
        throw;
    }
}

4.

void CallingMethod()
{
    try
    {
        throw new Exception( "TEST" );
    }
    catch( Exception ex )
    {
        throw new Exception( "RETHROW", ex );
    }
}

案例1和案例2将为您提供一个堆栈跟踪,其中CallingMethod方法的源代码行号是抛出新异常(“TEST”)行的行号。

然而,情形3将为您提供一个堆栈跟踪,其中CallingMethod方法的源代码行号是抛出调用的行号。这意味着如果抛出新的异常(“TEST”)行被其他操作包围,则您不知道异常实际上是在第几行抛出的。

情况4与情况2类似,因为原始异常的行号被保留,但不是真正的重抛出,因为它改变了原始异常的类型。