Question

I'm investigating a bit about how the unhandled exceptions are managed in .Net and I'm getting unexpected results that I would like to share with you to see what do you think about.

The first one is pretty simple to see. I wrote this code to do the test, just a button that throws an Exception on the same thread that created the Form:

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Throw New Exception()
    End Sub

    Private Sub UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
        MsgBox(String.Format("Exception: {0}. Ending: {1}. AppDomain: {2}", CType(e.ExceptionObject, Exception).Message, e.IsTerminating.ToString(), AppDomain.CurrentDomain.FriendlyName))
    End Sub

    Private Sub UnhandledThreadException(ByVal sender As Object, ByVal e As System.Threading.ThreadExceptionEventArgs)
        MsgBox(String.Format("Exception: {0}. AppDomain: {1}", e.Exception.Message(), AppDomain.CurrentDomain.FriendlyName))
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf UnhandledException
        AddHandler Application.ThreadException, AddressOf UnhandledThreadException
    End Sub
End Class

When I execute the code inside the Visual Studio the UnhandledException is called as expected but when I execute the application from Windows the UndhanledThreadException is called instead. ¿?¿?¿¿?¿?

Someone has any idea of what can be happening here?

Thanks in advance.

EDIT: After reading Application.ThreadException documentation looks like Application.ThreadException is raised when exceptions happen inside "Windows Forms threads" (whatever they are, IMHO there is only one Windows Form thread in each app). So Application.ThreadException is related to Exceptions thrown from the thread that created the Form of your application and the other exceptions are handled by the AppDomain.CurrentDomain.UnhandledException.

Was it helpful?

Solution

Yes, this is normal. The Application.ThreadException catcher is disabled when you run under a debugger. This is done so you can easily diagnose exceptions. To make it behave the same way, you have to call the Application.SetUnhandledExceptionMode() method. Unfortunately that's hard to do in a VB.NET project, you have to disable the application framework.

Not worth the hassle, press Ctrl+F5 if you want to test the exception handling code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top