Sign in to follow this  
chot

[.net] Rethrowing exception without losing stack trace

Recommended Posts

Hi, In my application a lot of the code is executed within a MethodInfo.Invoke, and whenever an exception occurs within that code it gets trapped in a TargetInvocationException, thus preventing the visual studio debugger from showing the real problem. I could of course find the source manually by examining the StackTrace of the inner exception, but as I said, most of my code is within an Invoke and thus I really want to be able to use the visual studio debugger. I've searched the net for some way of rethrowing the inner exception and keeping the stack without any luck, so now I'm hoping someone here knows anything about this? So, here's an example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public void Test()
        {
            throw new Exception();
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p.GetType().GetMethod("Test").Invoke(p, null);
        }
    }
}

The exception is thrown in the Invoke line, but I want it to be displayed at the throw line. What I've found so far is this code (and variations of it) but it doesn't seem to work the way I want it to (i.e. displaying the exception debugger at the original exception in vs): http://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace Also, some articles says that just doing a throw; rethrow would preserve the stacktrace, but i guess it wouldn't work with an inner exception. Thank you for your help, Chot

Share this post


Link to post
Share on other sites
I am not certain this will work, as I don't have access to a windows machine right now to test. But I think it will work if you go into the Debug->Exceptions and set it to trap exceptions when they are thrown, rather than when they are unhandled. You have to set that on each type of exception you want to catch in invoked code, and you might get it trapping on some extra junk that will end up getting handled correctly.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this