Catching Unhandled Exceptions using C#

This example shows how to manage all exceptions that haven't been caught in the try-catch sections (in Windows Forms application).

The UnhandledException event handles uncaught exceptions thrown from the main UI thread. The ThreadException event handles uncaught exceptions thrown from non-UI threads.

  1. static void Main()   
  2. {  
  3.     Application.EnableVisualStyles();  
  4.     Application.SetCompatibleTextRenderingDefault(false);  
  5.   
  6.     Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);  
  7.     AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);  
  8.   
  9.     Application.Run(new Form1());  
  10. }  
  11.   
  12. static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)   
  13. {  
  14.     MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");  
  15.     // here you can log the exception ...    
  16. }  
  17.   
  18. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)   
  19. {  
  20.     MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception");  
  21.     // here you can log the exception ...    
  22. }