rheitzman rheitzman - 9 months ago 44
Vb.net Question

How to debug unhandle exception handling

My current install of Visual Studio 2015 will not allow me to throw an unhandled exception while running code from the IDE. I want to exercise my unhandled exception code but my code:

Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
Throw New System.Exception("An unhandled test exception has occurred.")
End Sub

only works during a normal runtime, not when the code is executed in the IDE.

How can I debug my unhandled exception code in the IDE?

I looked in Debug, Windows, Exception Settings but I don't see a way to do what I want to do. Is there another more global setting that will allow an unhandled exception without the IDE capturing the exception?

I'm using the ApplicationsEvents.vb to hook the event:

Namespace My

' The following events are available for MyApplication:
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed. This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active.
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication
Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
ExpLog.LogUnhandledException(e, sender)
e.ExitApplication = Not ExpLog.InformUser
End Sub
End Class
End Namespace

Resolution was to create a test stub that exercised the code that was called by the handler:

Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles btnMisc_Throw.Click

If ExpLog.InformUser() Then
MsgBox("End Program")
End If

ExpLog.LogMsgBox(New System.Exception("test unhandled exception"), "test LogMsgBox()",,, "programmer note")

End Sub

This doesn't allow for testing the handler but it does exercise the code the handler calls. Looking at some old comments I figured this out five+ years ago... :(

Answer Source

Add a handler to AppDomain.CurrentDomain.UnhandledException

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledExceptionHandler
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Throw New System.Exception("An unhandled test exception has occurred.")
End Sub

Public Shared Sub UnhandledExceptionHandler(ByVal sender As Object, ByVal args As UnhandledExceptionEventArgs)
    MessageBox.Show(CType(args.ExceptionObject, Exception).Message)
End Sub