2014-09-05 81 views
2

我尝试在异常之后继续执行Try块。
我的意思是:Catch块后继续

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

如果在action2发现错误去捕捉,做记录并继续action3action4;

我该怎么做?

回答

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 
+0

它hwould是好的,但有时我不得不与未知元素使用它。我的意思是在尝试中我必须使用foreach,并且必须回到你的try块并继续。 – Gabor85 2014-09-08 06:33:01

+0

@ Gabor85:你不能从'catch'回到'try'。你可以做的是在catch之后重复'try'(比如'ReTryTenTimes'函数)。你也可以这样做。例如:'Dim success = False Dim retries = 10 while Not success AndAlso retries <10 success = TryAction(AddressOf action1)If Not success Then retries + = 1 End While While' – 2014-09-08 06:52:15

0

移动尝试/捕获块到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 
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