在VB.NET中,如果从Catch返回一个值,那么Finally代码仍会执行吗?
例如(我已经将这段代码概括了一下):
Try response = Client.doRequest() Catch ex As Exception 'Request threw an error - Fatal failure. InsertErrorLog(ex) Return False Finally DisposeClient() End Try
我需要确保DisposeClient()始终执行.因为我要退出Catch,最终还是会被执行吗?
最后总是执行块,无论代码是否执行到Catch块.
参见:https://msdn.microsoft.com/en-us/library/fk6t46tz.aspx
尝试使用此代码:
Dim Temp As String Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click Temp = "A" MessageBox.Show(Test()) MessageBox.Show(Temp) End Sub Private Function Test() As String Try Temp = "B" Throw New Exception() Temp = "C" Return "Try" Catch ex As Exception Temp = "D" Return "Catch" Finally Temp = "E" End Try Temp = "F" Return "End" End Function
它显示消息:
Catch
然后
E
这意味着,即使函数在Catch块返回,也始终执行finally块.