yoy.be "Why-o-Why"

How to keep an exception from killing the application.

2006-12-22 11:18  i1037  dotnet  [permalink]

When exception occurs, and isn't handled in the event handler of the application, the exception message pops up, and then the application teminates.

For those who develop in Delphi this might be unexpected. There it's accustomed that, after the exception popup, the application is allowed to keep running and only the handling of the current event is interrupted.

Perhaps this is a point of difference between other development environments also. And as I recall this was an important difference with VB6 also. So perhaps it is part of the Microsoft philosophy.

The way around this is not that hard: add this line somewhere up front the event handler of the Form.Load event:

Application.ThreadException+=new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

Or just type Application.ThreadException+= and press Tab twice to auto-generate the handler.

In the handler, type this code:

MessageBox.Show(this,e.Exception.ToString(),"Exception occurred",MessageBoxButtons.OK,MessageBoxIcon.Error);

This will display the error in a plain MessageBox, but not halt the application.

(This code is in [[C#]], anybody care to add the [[VB.Net]] version? hit edit on this page!)

twitter reddit linkedin facebook