开发者

Capturing unhandled exceptions in .Net 2.0. Wrong event called

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜