Does anyone have a proven formula for global exception handing in a C# Windows Forms application?
Global meaning "in one place" e.g. not multiple try...catches e.g. on each event handler. Proven meaning "known to work" - I'm aware covering both .NET and other exceptions is not straightforward.
Thanks.
Solution coded from answers below.
Note: this is believed to cover exceptions from additional threads.
static class Program
{
static void MyHandler(Exception e)
{ MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
static void MyThreadExceptionEventHandler(object sender, ThreadExceptionEventArgs args)
{ MyHandler(args.Exception);
// App continues.
}
static void MyAppExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{ MyHandler((Exception)args.ExceptionObject);
// There follows a OS "needs to close" dialog, terminating app.
}
static void Main()
{
// For UI thread exceptions
Application.ThreadException +=
new ThreadExceptionEventHandler(MyThreadExceptionEventHandler);
// Force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// For non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(MyAppExceptionHandler);
Application.SetCompatibleText开发者_运维技巧RenderingDefault(false);
Application.Run(new Form1());
}
}
The default behavior when it displays error dialog on unhandled exception and terminates is a good formula. If you don't like the look and feel of this dialog you can show your own instead but the principle is the same (good example is here):
public static void Main(string[] args)
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException
+= new ThreadExceptionEventHandler(/* YOUR OWN HANDLER */);
// Set the unhandled exception mode to force all
// Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(/* YOUR OWN HANDLER */);
// Runs the application.
Application.Run(new /* YOUR MAIN FORM*/);
}
Generally there is no magic 'solution' to exception handling - you have to think about handling specific exceptions before calling any method. There is nothing special about Windows Forms in this regard.
Handle the AppDomain.CurrentDomain.UnhandledException and the Application.ThreadException you should be good!
Use Exception Handling Application Block and exception policy that may be adjusted in config file. I like it but it might be 'too heavy' for someone when considering very small projects.
精彩评论