BackgroundWorker vs Try/Catch?

Hi. I have an app that spawns a couple of BackgroundWorkers. The process works perfectly when all the target servers are available.

For testing purposes, I added some non-existant servers to the mix.

The problem is in the Try/Catch block of the background process. I have to connect to a SQL Server first, then do stuff. Even though I handle the problem to gracefully exit, I keep getting the message in Debug mode.

TargetInvocationException was unhandled
- Exception has been thrown by the target of an invocation.
-InnerException.Message: {"Object reference not set to an instance of an object."}

I thought maybe this was a noob question similar to VB6's option "Break on all errors/Break on unhandled errors," but I don't have ths problem on first-level Try/Catch blocks.

Simplified Code:

Function Catalog_Datasource( _
ByVal Datasource As String, _
ByVal worker As BackgroundWorker, _
ByVal e As DoWorkEventArgs) As String

Dim result as String = ""

Try
'Connect to SQL Server
Catch ex As Exception
GoTo Err_Handler
End Try

'do stuff <- I hit the error doing stuff
result = "Completed"

Return result
Exit Function

Err_Handler:
result = "Error"

End Function



Answer this question

BackgroundWorker vs Try/Catch?

  • Celios

    Good grief... this is a noob question...nothing to do with the Backgroundworker.

    I need to Return the error, otherwise it will keep going. Thanks for the feedback, it got my brain to jogging when your example worked.

    Function Catalog_Datasource( _
    ByVal Datasource As String, _
    ByVal worker As BackgroundWorker, _
    ByVal e As DoWorkEventArgs) As String

    Dim result as String = ""

    Try
    'Connect to SQL Server
    Catch ex As Exception
    GoTo Err_Handler
    End Try

    'do stuff
    result = "Completed"

    Return result
    Exit Function

    Err_Handler:
    result = "Error"
    Return result

    End Function


  • Saravanan.Chinnusamy

    I don't see any error handling where you say you're getting an error, perhaps this is due to your simplified code. I'd also not recommend putting a GoTo in your Catch section.

    What I'd recommend using a Try...Catch block for the entire routine, not just a small section of it. Something like this:

    Function Catalog_Datasource( _
    ByVal Datasource As String, _
    ByVal worker As BackgroundWorker, _
    ByVal e As DoWorkEventArgs) As String

    Dim result as String = ""

    Try
    'Connect to SQL Server
    'do stuff
    result = "Completed"
    Catch ex As Exception
    result = "Error"
    End Try
    Return result
    End Function



  • BackgroundWorker vs Try/Catch?