views:

98

answers:

1

Hello,

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.

+2  A: 

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.

Hans Passant
No problem debugging the handling code, it's just that I didn't found any documentation about that fact. Anyway, just tried the SetUnHandledException and the handler is not called anyway because execution stops at the Exception origin point and can not go further.
SoMoS