My.Application.UnhandledException Event is the way for handling all unhandled exceptions in an windows forms application. The application raises this event when it encounters unhandled exception.
For using the event editing ApplicationEvents.vb file is needed. By default ApplicationEvents.vb is hidden. For openning (unhiding) it use Project Properties -> Application tab -> View Appication Events.
Then the handler can be added/edited as in the example below:
And from now on all unhandled exception in the application will be stored as exception information and stack trace in the application log file or in the Windows Event log and the user will receive friendly message.
Private Sub MyApplication_UnhandledException( _
ByVal sender As Object, _
ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs _
) Handles Me.UnhandledException
//write log, which is nessted in Application Data folder
//check up if the Event folder exists.
//if not - create new one
If Not EventLog.SourceExists("My software") Then
EventLog.CreateEventSource("My software", "My Software")
//write event log, can be seen by Event Viewer
EventLog.WriteEntry("My software", _
Catch ex As Exception
// code for notifying the user with user friendly message
//set the default application action (closing) not to be performed.
e.ExitApplication = False
Of course most of my posts give examples with VB and C# when they are different. Now I will give up this pleasure to R. Newman with his great post "Top-level Exception Handling in Windows Forms Applications"