Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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!

Posted

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:

 
//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:

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:

public void LogError( Exception currentException )
{
  //do your logic to log the error (or whatever)
  ......

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...