Fatal Errors

RobEmDee

Centurion
Joined
Mar 25, 2003
Messages
130
Location
Richmond, VA
I am working back through an application I coded trying enhance the error handling and recovery. In any instance where something really bad has happened and following an error message to the user, I'd like to point the error handling to a global static method that will completely shut down the application. I can think of a few ways to do this, but wanted to solicit some feedback from others on how they handle this in their Windows Forms applications.

Thanks!
 
You can attach an event-handler to your applacation thread like this - this piece goes somewhere really early in the app code - like the Main() or constructor of your first window:
Code:
//global try/catch handler to catch any unhandled exceptions anywhere in app
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler( this.GlobalExceptionTrap );

then the function looks like this:
Code:
public void GlobalExceptionTrap( Object sender , System.Threading.ThreadExceptionEventArgs e )
{
   //call error routine to write error to event-log or database, etc:
   LogError( e.Exception );
}

...edit..
Oh, and you asked how to kill the app - that's done like this:
Code:
public void LogError( Exception currentException )
{
   //do your logic to log the error (or whatever)
   ......

   //Close the application
   Process.GetCurrentProcess().Kill();
}
 
Back
Top