Dim eh As CustomExceptionHandler = New CustomExceptionHandler()
' Adds the event handler to the event.
AddHandler Application.ThreadException, AddressOf eh.OnThreadException
' Creates a class to handle the exception event.
Private Class CustomExceptionHandler
' Handles the exception event.
Public Sub OnThreadException(ByVal sender As Object, ByVal t As System.Threading.ThreadExceptionEventArgs)
Dim result As DialogResult = System.Windows.Forms.DialogResult.Cancel
Try
result = Me.ShowThreadExceptionDialog(t.Exception)
Catch
Try
MessageBox.Show("Fatal Error", "Fatal Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
Finally
Application.Exit()
End Try
End Try
' Exits the program when the user clicks Abort.
If (result = System.Windows.Forms.DialogResult.Abort) Then
Application.Exit()
End If
End Sub
' Creates the error message and displays it.
Private Function ShowThreadExceptionDialog(ByVal e As Exception) As DialogResult
Dim errorMsg As String = "An error occurred please contact the administrator with the following information:" & vbCrLf & vbCrLf
errorMsg &= e.Message & vbCrLf
errorMsg &= "Stack Trace:" & vbCrLf
errorMsg &= e.StackTrace & vbCrLf
Return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop)
End Function
End Class