This will catch any exception that you do not explicitly handle. Not only can you gather information about the state of the application when the exception is thrown, but it also gives you a chance to shut down the app cleanly.
VB Code:
Imports System.Threading Public Class frmMain Inherits System.Windows.Forms.Form '//Windows Form Designer generated code Public Shared Sub Main() Dim frm As New frmMain 'Install a ThreadException Handler AddHandler Application.ThreadException, _ New ThreadExceptionEventHandler(AddressOf frm.GlobalErrorProc) 'Run the main form Application.Run(frm) End Sub Public Sub GlobalErrorProc(ByVal sender As Object, _ ByVal args As ThreadExceptionEventArgs) 'Inform the user of the exception, and allow the application to close nicely MessageBox.Show("An unhandled exception has occured: " & args.Exception.Message, _ "Unhandled Exception", MessageBoxButtons.OK, MessageBoxIcon.Error) Me.Close() Application.Exit() 'You could also write the stack trace out to a file or something at this for 'debugging purposes, or gather any other state info that you want End Sub Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click 'Just to test it out, throw an exception Throw New Exception("This is a test") End Sub End Class




Reply With Quote