我正在调查.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中执行代码时,将按预期调用未处理的异常,但当我从windows执行应用程序时,将改为调用undhanledthreadexception。是吗?是吗?是什么?什么?
有人知道这里会发生什么吗?
提前谢谢。
编辑:阅读后
Application.ThreadException documentation
看起来application.threadexception是在“windows窗体线程”中发生异常时引发的(不管它们是什么,imho每个应用中只有一个windows窗体线程)。因此application.threadexception与创建应用程序窗体的线程引发的异常相关,其他异常由appdomain.currentdomain.unhandledeexception处理。