我嘗試在異常之後繼續執行Try
塊。
我的意思是:Catch塊後繼續
Try
action1()
action2()
action3()
action4()
Catch
Log()
如果在action2
發現錯誤去捕捉,做記錄並繼續action3
,action4
;
我該怎麼做?
我嘗試在異常之後繼續執行Try
塊。
我的意思是:Catch塊後繼續
Try
action1()
action2()
action3()
action4()
Catch
Log()
如果在action2
發現錯誤去捕捉,做記錄並繼續action3
,action4
;
我該怎麼做?
您可以使用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
移動嘗試/捕獲塊到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
下面是一個例子使用數組:
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
它hwould是好的,但有時我不得不與未知元素使用它。我的意思是在嘗試中我必須使用foreach,並且必須回到你的try塊並繼續。 – Gabor85 2014-09-08 06:33:01
@ 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