views:

78

answers:

2

I am looking for a way to retrieve the current exception without having to pass it as a variable.

Suppose the following code

public void MakeItFail()
{
    try
    {
        throw new FailException();
    }
    catch // Yes I'm aware that this shouldn't be done, but I don't want to go through all the code base and change it
    {
        ShowMessage("An error occured");
    }
}

public void ShowMessage(string message)
{
    // How can I retrieve the exception here
}

In the watch window, I can use $exception to get the current exception. Is there is a code equivalent?

+4  A: 

No, there isn't.

You need to use a parameter.

SLaks
I've read about some possible but hard way using the ICorDebugThread.GetCurrentException() but I didn't try it.
Pierre-Alain Vigeant
That's part of the unmanaged debugger API. You can only use it on a process that's paused in a debugger. Since a process cannot debug itself, you'd need to write a second process to debug the first one and call that API.
SLaks
And I am not going down that rabbit hole :P
Pierre-Alain Vigeant
Very good idea.
SLaks
This is the choosen answer because we assigned someone to changes all catch block to properly pass the exception to our feedback system.
Pierre-Alain Vigeant
A: 

Try subscribing to this event when you first load your app.

AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
{
    ShowMessage(e.Exception.Message);
};
ChaosPandion
aww that.net 4 only. This is an existing program and we are not converting it to 4.0 yet
Pierre-Alain Vigeant
@Pierre - Just another reason good reason to upgrade...
ChaosPandion
I know. I wish I could :(
Pierre-Alain Vigeant
Great, another security hole...
Steven Sudit