HELP!!! Exception handler only working from VS IDE

  • Thread starter Thread starter Tim Greenwood
  • Start date Start date
T

Tim Greenwood

I've wrapped a try/catch around the code in my Main function of a windows
app. I'm catching several custom exception classes specifically. I raise
one of these in my program to test and all seems fine. The exception is
caught and I can display an appropriate message. At least as long as I'm
running in the VS IDE!!!! As soon as I run the .EXE standalone I get the
standard "Unhandled exception" message. Why would this behave differently??
 
This is a bit of a WAG, but here goes: (assuming that you have a WinForm
application, and not a console app)

If you catch the exception outside of Application.Run, in Main:
try
{
Application.Run(new Form());
}
catch
{
}

That would mean that in order to catch the exception, it must be elevated
outside of your main message loop. I expect that something in Winforms
assumes that an exception that gets out of the main form's message loop is
an unhandled exception. I'm not sure why it behaves differently in the
debugger.

Now, regardless of the "why". I think that you probably don't want to leave
the main message loop that way. Instead, hook the
Application.ThreadException event:

public void Main()
{
Application.ThreadException event before the call to Run:
Application.ThreadException += new
ThreadExceptionEventHandler(YourErrorHandler) ;
Application.Run(new Form());
}

If the nature of the exception is such that the application should close,
you can trigger a shutdown of your application with a call
Application.Exit() inside of your ThreadExceptionEventHandler. Note: when
you call Application.Exit, your form Closing and Closed events will not be
fired.
 
I thought it might have to do with the message loop but wasn't sure how to
circumvent that. Thanks for the input. This fixes it up nicely.
 
J.Marsch said:
This is a bit of a WAG, but here goes: (assuming that you have a WinForm
application, and not a console app)

Do you know of a similar mechanism for a console application?

-- Alan
 
Alan:

I've not tried to use the Application.ThreadException event for a console
application. It might work as-is. If not, I _think_ that it's safe to just
use a try..catch block inside of Main for a console app. I put the
exception on console apps in there because I didn't think that it should be
a problem with a console app, and if it was, I wouldn't know the reason why.

Regards
-- Jeremy
 
Back
Top