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.
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.