Does anyone have a proven formula for handling global exceptions in a C # Windows Forms application?

The global meaning of "in one place", for example. not a few attempts ... catches, for example. on each event handler. The proven meaning of โ€œknown to workโ€ - I know that covering both .NET and other exceptions is not straightforward.

Thanks.

The solution encoded from the answers below.

Note. This is believed to apply to 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.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } 
+4
source share
3 answers

Handle AppDomain.CurrentDomain.UnhandledException and Application.ThreadException, you should be good!

+2
source

The default behavior when displaying an error dialog box in an unhandled exception and termination is a good formula . If you don't like the look of this dialog, you can show your own instead , but the principle is the same (a good example 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*/); } 

Typically, there is no โ€œsolutionโ€ for handling exceptions - you should consider handling special exceptions before calling any method. There is nothing special about Windows Forms in this regard.

+3
source

Use an exception handling block and exclude an exception policy that can be adjusted in the configuration file. I like it, but it can be "too hard" for someone when considering very small projects.

0
source

All Articles