# [.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.

## 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 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 on other sites
Seems to work like a charm! :D Thank you very much!!

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5

• 13
• 19
• 14
• 9
• 9
• ### Forum Statistics

• Total Topics
632930
• Total Posts
3009289
• ### Who's Online (See full list)

There are no registered users currently online

×