Exception handling and the backgroundworker

I'm using VB in Forms 2.0 and have some strange problems with exception handling in combination with the background worker.

I have added two exception handlers:
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnUnhandledException
AddHandler Application.ThreadException, AddressOf OnThreadException

When an exception is raised on a background thread (started using the backgroundworker), I want to be able to handle it nicely on the UI-thread. The exceptions are not always fatal, needing the application to exit.

When the background thread has finished executing, I'm checking the e.Error value to
see if an exception occurred on the background thread. If it has, I want the exception
to take "the normal way" as other exceptions that might occur on my UI-thread so I can
handle them the same way.

Private Sub BackgroundWorker1_RunWorkerCompleted(...) handles BackgroundWorker1.RunWorkerCompleted

If e.Error IsNot Nothing Then Throw e.Error

End Sub

Running the program from an .exe works just at intended. The OnThreadException method "catches" the exception and the type of exception is the one originally raised.

BUT!!! When I run the same program i debugmode (in VS2005). The error "becomes" a TargetInvocationException (with the original exception as innerexception). The method OnUnhandledException "catches" the exception this time and then TERMINATES the app.

How I am going to handle this What am I doing wrong There must be thousands of developers needing the same functionality...

Regards
-tomas.




Answer this question

Exception handling and the backgroundworker

  • Volker Gerdes

    The call stack of the outer TargetInvocationException should answer your question for you.

  • Exception handling and the backgroundworker