我正在研究如何在 .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 处理。