views:

49

answers:

1

Is there an elegant way to trap all unhandled exceptions in a Windows Form application? I would like to handle them and write them to a log file. I know ASP.NET has one. I'm using C#.

+1  A: 

To trap uncaught exceptions on UI threads only, you can use Application.ThreadException event.

To trap uncaught exceptions on all threads in the appdomain, use AppDomain.Current.UnhandledException. The latter won't let you swallow the exception, however - you can log it in the handler, but once it returns, the exception will be handed over to Watson, which will display the usual Win32 crash dialog.

Pavel Minaev
How would I supress it if I use the second way?
Daniel A. White
You cannot do that, which is by design. In fact, you shouldn't - Windows application guidelines (which you _need_ to follow if you want "Certified for Vista" sticker for your app, and might want to follow anyway 'cause it's _the_ guide to how well-behaved Windows apps should behave) specifically say that errors should be reported via Watson.
Pavel Minaev
So I guess I better catch all exception.
Daniel A. White