views:

647

answers:

2

A C# program is invoked by:

Application.Run (new formClass ());

I'd like to put a try/catch around the whole thing to trap any uncaught exceptions. When I put it around this Run method, exceptions are not caught; control only returns here when the program terminates after an uncaught exception.

Where can I put try/catch to cover the whole program? Thanks!

+28  A: 

To catch Windows Form's unhandled exceptions hook-up the AppDomain.UnhandledException and Application.ThreadException events.

Of interest: Unexpected Errors in Managed Applications

Mitch Wheat
@alankdkd: Make sure you read to the end and the "Some Best Practices" section ;)
Lazarus
You cannot catch an exception with `AppDomain.UnhandledException` (it will still terminate the application), but rather just get notified. This is an important difference compared to `Application.ThreadException` which is an exception catch.
Lucero
I can't get UnhandledException to work. I've tried:<pre>AppDomain currentDomain = AppDomain.CurrentDomain;currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);</pre>But when there's an exception, MyHandler is never called.I'll try ThreadException...
ThreadException worked! Thanks Mitch! You get points.
Another great one!
Ashley Tate
+5  A: 

Basically, you cannot catch all exceptions when using the default CLR hosting process. Period. This is because the AppDomain.UnhandledException event is a notification only, you cannot handle the exception (which means that you cannot prevent the application from being terminated after processing the notification).

However, you can catch and handle all exceptions in the UI thread of a WinForms application by using its Application.ThreadException handler (and control the behavior via UnhandledExceptionMode). Other threads which throw an exception will not be caught by this handler.

In general, it's not a good idea to try and handle all exceptions. You can, however, use the AppDomain.UnhandledException to log the error and/or perform important cleanup tasks (e.g. shutting down a file-based databaseor whatever).

Lucero