Capturing unhandled exceptions in .Net 2.0. Wrong event called.

Posted by SoMoS on Stack Overflow See other posts from Stack Overflow or by SoMoS
Published on 2010-04-12T10:21:27Z Indexed on 2010/04/12 10:23 UTC
Read the original article Hit count: 715

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.

© Stack Overflow or respective owner

Related posts about unhandled-exception

Related posts about exception