0

I have a piece of code in my ApplicationEvents.vb that is supposed to handle all exceptions:

Namespace My

' The following events are available for MyApplication:
' 
' Startup: Raised when the application starts, before the startup form is created.
' Shutdown: Raised after all application forms are closed.  This event is not raised if the application terminates abnormally.
' UnhandledException: Raised if the application encounters an unhandled exception.
' StartupNextInstance: Raised when launching a single-instance application and the application is already active. 
' NetworkAvailabilityChanged: Raised when the network connection is connected or disconnected.
Partial Friend Class MyApplication

    Private Delegate Sub SafeApplicationThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)

    Private Sub ShowDebugOutput(ByVal ex As Exception)

        Dim frmD As New frmDebug()
        frmD.rtfError.AppendText(ex.ToString())
        frmD.ShowDialog()

        Environment.Exit(0)

    End Sub

    Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup

        System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)

        AddHandler System.Windows.Forms.Application.ThreadException, AddressOf app_ThreadException


        AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf AppDomain_UnhandledException
    End Sub

    Private Sub app_ThreadException(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)


        If MainForm.InvokeRequired Then

            MainForm.Invoke(New SafeApplicationThreadException(AddressOf app_ThreadException), New Object() {sender, e})
        Else
            ShowDebugOutput(e.Exception)
        End If

    End Sub

    Private Sub AppDomain_UnhandledException(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)

        ShowDebugOutput(DirectCast(e.ExceptionObject, Exception))

    End Sub

    Private Sub MyApplication_UnhandledException(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException

        ShowDebugOutput(e.Exception)

    End Sub

End Class


End Namespace

However, i have found that it will not catch exceptions from within, for example, a BGWorker_DoWork sub.

It will, however, catch exceptions on the same BGWorker_RunWorkerCompleted sub.

Is there a way for me to catch the exceptions from within the thread, without using Try-Catch?

Gematria
  • 105
  • 1
  • 14
  • For handling backgroundworker exception, consider e.Error on completed event. http://stackoverflow.com/questions/1044460/unhandled-exceptions-in-backgroundworker – Mehrzad Chehraz Apr 25 '15 at 19:05
  • Guess theres no way to do what id like then, but at least this helps :) Thanks. – Gematria Apr 25 '15 at 19:18

0 Answers0