Catch块后继续

时间:2014-09-05 15:01:59

标签: vb.net try-catch

我尝试在异常后继续Try阻止 我的意思是:

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

如果action2中发现错误转到Catch,请记录并继续action3action4;

我该怎么做?

3 个答案:

答案 0 :(得分:1)

以下是使用数组的示例:

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

答案 1 :(得分:0)

您可以使用Action作为此方法的参数:

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

现在可行:

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

使用多个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

答案 2 :(得分:0)

将Try / Catch块移动到Action()方法中。这将允许您在必要时以不同方式响应每种方法中的异常。

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