2

我正在研究如何在 .Net 中管理未处理的异常,我得到了意想不到的结果,我想与您分享一下您的想法。

第一个很容易看到。我编写了这段代码来进行测试,只是一个在创建表单的线程上引发异常的按钮:

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

当我在 Visual Studio 中执行代码时,会按预期调用 UnhandledException,但是当我从 Windows 执行应用程序时,会调用 UndhanledThreadException。¿?¿?¿¿?¿?

有人知道这里会发生什么吗?

提前致谢。

编辑:阅读Application.ThreadException 文档后,当“Windows 窗体线程”内发生异常时,会引发 Application.ThreadException(无论它们是什么,恕我直言,每个应用程序中只有一个 Windows 窗体线程)。因此 Application.ThreadException 与创建应用程序表单的线程抛出的异常有关,其他异常由 AppDomain.CurrentDomain.UnhandledException 处理。

4

1 回答 1

2

是的,这很正常。当您在调试器下运行时,Application.ThreadException 捕获器被禁用。这样做是为了方便您诊断异常。要使其行为相同,您必须调用Application.SetUnhandledExceptionMode() 方法。不幸的是,这在 VB.NET 项目中很难做到,您必须禁用应用程序框架。

不值得麻烦,如果要测试异常处理代码,请按 Ctrl+F5。

于 2010-04-12T11:56:01.870 回答