Jump to content
  • Advertisement
Sign in to follow this  
chot

[.net] Rethrowing exception without losing stack trace

This topic is 3559 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!