<p>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?<br>
I am rethrowing the InnerException, but this destroys the stack trace.<br>
Example code:</p>

<pre><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;
    }
}
</code></pre>

[{'answer_id': 57387, 'author': 'GEOCHET', 'author_id': 5640, 'author_profile': 'https://Stackoverflow.com/users/5640', 'pm_score': 5, 'selected': False, 'text': '<p>I think your best bet would be to just put this in your catch block:</p>\n\n<pre><code>throw;\n</code></pre>\n\n<p>And then extract the innerexception later.</p>\n'}, {'answer_id': 57389, 'author': 'skolima', 'author_id': 3205, 'author_profile': 'https://Stackoverflow.com/users/3205', 'pm_score': 4, 'selected': False, 'text': '<p>Even more reflection...</p>\n\n<pre><code>catch (TargetInvocationException tiex)\n{\n    // Get the _remoteStackTraceString of the Exception class\n    FieldInfo remoteStackTraceString = typeof(Exception)\n        .GetField("_remoteStackTraceString",\n            BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net\n\n    if (remoteStackTraceString == null)\n        remoteStackTraceString = typeof(Exception)\n        .GetField("remote_stack_trace",\n            BindingFlags.Instance | BindingFlags.NonPublic); // Mono\n\n    // Set the InnerException._remoteStackTraceString\n    // to the current InnerException.StackTrace\n    remoteStackTraceString.SetValue(tiex.InnerException,\n        tiex.InnerException.StackTrace + Environment.NewLine);\n\n    // Throw the new exception\n    throw tiex.InnerException;\n}\n</code></pre>\n\n<p>Keep in mind that this may break at any time, as private fields are not part of API. See further discussion on <a href="https://bugzilla.novell.com/show_bug.cgi?id=425512" rel="nofollow noreferrer">Mono bugzilla</a>.</p>\n'}, {'answer_id': 57394, 'author': 'kokos', 'author_id': 1065, 'author_profile': 'https://Stackoverflow.com/users/1065', 'pm_score': 4, 'selected': False, 'text': "<p>First: don't lose the TargetInvocationException - it's valuable information when you will want to debug things.<br>\nSecond: Wrap the TIE as InnerException in your own exception type and put an OriginalException property that links to what you need (and keep the entire callstack intact).<br>\nThird: Let the TIE bubble out of your method.</p>\n"}, {'answer_id': 1663549, 'author': 'Eric', 'author_id': 201208, 'author_profile': 'https://Stackoverflow.com/users/201208', 'pm_score': 4, 'selected': False, 'text': '<pre><code>public static class ExceptionHelper\n{\n    private static Action&lt;Exception&gt; _preserveInternalException;\n\n    static ExceptionHelper()\n    {\n        MethodInfo preserveStackTrace = typeof( Exception ).GetMethod( "InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic );\n        _preserveInternalException = (Action&lt;Exception&gt;)Delegate.CreateDelegate( typeof( Action&lt;Exception&gt; ), preserveStackTrace );            \n    }\n\n    public static void PreserveStackTrace( this Exception ex )\n    {\n        _preserveInternalException( ex );\n    }\n}\n</code></pre>\n\n<p>Call the extension method on your exception before you throw it, it will preserve the original stack trace.</p>\n'}, {'answer_id': 1992235, 'author': 'Boris Treukhov', 'author_id': 241986, 'author_profile': 'https://Stackoverflow.com/users/241986', 'pm_score': 3, 'selected': False, 'text': '<p>Guys, you are cool.. I\'m gonna be a necromancer soon.</p>\n\n<pre><code>    public void test1()\n    {\n        // Throw an exception for testing purposes\n        throw new ArgumentException("test1");\n    }\n\n    void test2()\n    {\n            MethodInfo mi = typeof(Program).GetMethod("test1");\n            ((Action)Delegate.CreateDelegate(typeof(Action), mi))();\n\n    }\n</code></pre>\n'}, {'answer_id': 2085377, 'author': 'Anton Tykhyy', 'author_id': 77724, 'author_profile': 'https://Stackoverflow.com/users/77724', 'pm_score': 6, 'selected': False, 'text': '<p>It <strong>is</strong> possible to preserve the stack trace before rethrowing without reflection:</p>\n\n<pre><code>static void PreserveStackTrace (Exception e)\n{\n    var ctx = new StreamingContext  (StreamingContextStates.CrossAppDomain) ;\n    var mgr = new ObjectManager     (null, ctx) ;\n    var si  = new SerializationInfo (e.GetType (), new FormatterConverter ()) ;\n\n    e.GetObjectData    (si, ctx)  ;\n    mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData\n    mgr.DoFixups       ()         ; // ObjectManager calls SetObjectData\n\n    // voila, e is unmodified save for _remoteStackTraceString\n}\n</code></pre>\n\n<p>This wastes a lot of cycles compared to calling <code>InternalPreserveStackTrace</code> via cached delegate, but has the advantage of relying only on public functionality. Here are a couple of common usage patterns for stack-trace preserving functions:</p>\n\n<pre><code>// usage (A): cross-thread invoke, messaging, custom task schedulers etc.\ncatch (Exception e)\n{\n    PreserveStackTrace (e) ;\n\n    // store exception to be re-thrown later,\n    // possibly in a different thread\n    operationResult.Exception = e ;\n}\n\n// usage (B): after calling MethodInfo.Invoke() and the like\ncatch (TargetInvocationException tiex)\n{\n    PreserveStackTrace (tiex.InnerException) ;\n\n    // unwrap TargetInvocationException, so that typed catch clauses \n    // in library/3rd-party code can work correctly;\n    // new stack trace is appended to existing one\n    throw tiex.InnerException ;\n}\n</code></pre>\n'}, {'answer_id': 9989557, 'author': 'chickenbyproduct', 'author_id': 1309889, 'author_profile': 'https://Stackoverflow.com/users/1309889', 'pm_score': 2, 'selected': False, 'text': '<p>Anpother sample code which uses exception serialization/deserialization.\nIt does not require the actual exception type to be serializable.\nAlso it uses only public/protected methods.</p>\n\n<pre><code>    static void PreserveStackTrace(Exception e)\n    {\n        var ctx = new StreamingContext(StreamingContextStates.CrossAppDomain);\n        var si = new SerializationInfo(typeof(Exception), new FormatterConverter());\n        var ctor = typeof(Exception).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);\n\n        e.GetObjectData(si, ctx);\n        ctor.Invoke(e, new object[] { si, ctx });\n    }\n</code></pre>\n'}, {'answer_id': 17091351, 'author': 'Paul Turner', 'author_id': 138578, 'author_profile': 'https://Stackoverflow.com/users/138578', 'pm_score': 10, 'selected': True, 'text': '<p>In <strong>.NET 4.5</strong> there is now the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo" rel="noreferrer"><code>ExceptionDispatchInfo</code></a> class.</p>\n<p>This lets you capture an exception and re-throw it without changing the stack-trace:</p>\n<pre><code>using ExceptionDispatchInfo = \n    System.Runtime.ExceptionServices.ExceptionDispatchInfo;\n\ntry\n{\n    task.Wait();\n}\ncatch(AggregateException ex)\n{\n    ExceptionDispatchInfo.Capture(ex.InnerException).Throw();\n}\n</code></pre>\n<p>This works on any exception, not just <code>AggregateException</code>.</p>\n<p>It was introduced due to the <code>await</code> C# language feature, which unwraps the inner exceptions from <code>AggregateException</code> instances in order to make the asynchronous language features more like the synchronous language features.</p>\n'}, {'answer_id': 40586566, 'author': 'Mark', 'author_id': 6192931, 'author_profile': 'https://Stackoverflow.com/users/6192931', 'pm_score': 5, 'selected': False, 'text': '<p>Nobody has explained the difference between <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> and a plain <code>throw</code>, so here it is.</p>\n\n<p>The complete way to rethrow a caught exception is to use <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> (only available from .Net 4.5).</p>\n\n<p>Below there are the cases necessary to test this:</p>\n\n<p>1.</p>\n\n<pre><code>void CallingMethod()\n{\n    //try\n    {\n        throw new Exception( "TEST" );\n    }\n    //catch\n    {\n    //    throw;\n    }\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>void CallingMethod()\n{\n    try\n    {\n        throw new Exception( "TEST" );\n    }\n    catch( Exception ex )\n    {\n        ExceptionDispatchInfo.Capture( ex ).Throw();\n        throw; // So the compiler doesn\'t complain about methods which don\'t either return or throw.\n    }\n}\n</code></pre>\n\n<p>3.</p>\n\n<pre><code>void CallingMethod()\n{\n    try\n    {\n        throw new Exception( "TEST" );\n    }\n    catch\n    {\n        throw;\n    }\n}\n</code></pre>\n\n<p>4.</p>\n\n<pre><code>void CallingMethod()\n{\n    try\n    {\n        throw new Exception( "TEST" );\n    }\n    catch( Exception ex )\n    {\n        throw new Exception( "RETHROW", ex );\n    }\n}\n</code></pre>\n\n<p>Case 1 and case 2 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw new Exception( "TEST" )</code> line.</p>\n\n<p>However, case 3 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw</code> call. This means that if the <code>throw new Exception( "TEST" )</code> line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.</p>\n\n<p>Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.</p>\n'}, {'answer_id': 57052791, 'author': 'Jürgen Steinblock', 'author_id': 98491, 'author_profile': 'https://Stackoverflow.com/users/98491', 'pm_score': 4, 'selected': False, 'text': "<p>Based on Paul Turners answer I made an extension method</p>\n\n<pre><code>    public static Exception Capture(this Exception ex)\n    {\n        ExceptionDispatchInfo.Capture(ex).Throw();\n        return ex;\n    }\n</code></pre>\n\n<p>the <code>return ex</code> ist never reached but the advantage is that I can use <code>throw ex.Capture()</code> as a one liner so the compiler won't raise an <code>not all code paths return a value</code> error.</p>\n\n<pre><code>    public static object InvokeEx(this MethodInfo method, object obj, object[] parameters)\n    {\n        {\n            return method.Invoke(obj, parameters);\n        }\n        catch (TargetInvocationException ex) when (ex.InnerException != null)\n        {\n            throw ex.InnerException.Capture();\n        }\n    }\n</code></pre>\n"}, {'answer_id': 73625170, 'author': 'Ben', 'author_id': 723645, 'author_profile': 'https://Stackoverflow.com/users/723645', 'pm_score': 1, 'selected': False, 'text': "<p>This is just a nice clean, modern implementation of some of the other ideas here, tested in .NET 6:</p>\n<pre><code>public static class ExceptionExtensions\n{\n    [DoesNotReturn]\n    public static void Rethrow(this Exception ex) \n        =&gt; ExceptionDispatchInfo.Capture(ex).Throw();\n}\n</code></pre>\n<p>I wanted the value of the <code>PropertyName</code> property on <code>myObject</code> but this will work just as well when using reflection to call methods (as per OP's problem) or anything else that results in you wanting to re-throw an inner exception.</p>\n<pre><code>try\n{\n    object? value = myObject.GetType().GetProperty(&quot;PropertyName&quot;)?.GetValue(myObject);\n}\ncatch (TargetInvocationException ex)\n{\n    (ex.InnerException ?? ex).Rethrow();\n}\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/57383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3205/']