Try System.Windows.Forms.Application.Run(New Form1) Catch ex As Exception WriteErrorLogs(ex) End Try
Yes, this Catch clause will never catch an exception if you run it without a debugger attached. Exceptions that occur in the user interface thread are redirected and throw an Application.ThreadException event instead. What the dialog box displays by default, you should have noticed that when you started it from the bin \ Debug directory.
It works differently when you have a debugger installed, this dialog really gets in the way when you need to debug unhandled exceptions. Therefore, the ThreadException event is intentionally disabled, and the debugger shows you where your code crashed. What won't happen with the code you wrote now that the Catch clause blocks the exception.
The Catch clause will also not work if your program crashes due to an unhandled exception that has been raised in the workflow, it can only see exceptions in the user interface thread.
You will need a stronger approach, you can get it from the AppDomain.UnhandledException event. Which is caused for any unhandled exception, no matter what thread it was raised to. Make your code look like this:
Module Module1 Public Sub Main(ByVal args() As String) Application.EnableVisualStyles() Application.SetCompatibleTextRenderingDefault(False) If Not System.Diagnostics.Debugger.IsAttached Then Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException) AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf LogUnhandledExceptions End If Application.Run(New Form1()) End Sub Private Sub LogUnhandledExceptions(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs) Dim ex = DirectCast(e.ExceptionObject, Exception) '' Log or display ex.ToString() ''... Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(ex)) End Sub End Module
Using Debugger.IsAttached ensures that you can diagnose unhandled exceptions with a debugger. Using Application.SetUnhandledExceptionMode ensures that the dialog is never displayed and all exceptions are logged.
Hans passant
source share