Gabor85
Gabor85

Reputation: 135

Continue after Catch block

I try to continue the Try block after exception.
I mean:

Try
    action1()
    action2()
    action3()
    action4()
Catch
    Log()

And if found error in action2 go to Catch, do logging and continue with the action3, action4;

How can I do this?

Upvotes: 2

Views: 297

Answers (3)

Here's an example using array:

For Each a As Action In {New Action(AddressOf action1), New Action(AddressOf action2), New Action(AddressOf action3), New Action(AddressOf action4)}
    Try
        a.Invoke()
    Catch ex As Exception
        Log(ex)
    End Try
Next

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460370

You can use an Action as parameter for this method:

Public Shared Function TryAction(action As Action) As Boolean
    Dim success As Boolean = True
    Try
        action()
    Catch ex As Exception
        success = False
        Log()
    End Try
    Return success
End Function

Now this works:

TryAction(AddressOf action1)
TryAction(AddressOf action2)
TryAction(AddressOf action3)
TryAction(AddressOf action4)

The classic way using multiple Try-Catch:

Try
    action1()
Catch
    Log()
End Try
Try
    action2()
Catch
    Log()
End Try
Try
    action3()
Catch
    Log()
End Try
Try
    action4()
Catch
    Log()
End Try

Upvotes: 0

DWRoelands
DWRoelands

Reputation: 4940

Move the Try/Catch blocks into the Action() methods. This will allow you to respond to exceptions in each method differently, if necessary.

Sub Main()
  action1()
  action2()
  action3()
  action4()
End Sub

Sub Action1()
  Try
    '' do stuff
  Catch
    Log()
  End Try
End Sub

Sub Action2()
  Try
    '' do stuff
  Catch
    Log()
  End Try
End Sub

Sub Action3()
  Try
    '' do stuff
  Catch
    Log()
  End Try
End Sub

Sub Action4()
  Try
    '' do stuff
  Catch
    Log()
  End Try
End Sub

Upvotes: 0

Related Questions