尝试...捕获...最终在 VB.NET 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35600191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Try...Catch...Finally in VB.NET
提问by Virtual Anomaly
In VB.NET, if you return a value from the Catch, will the Finallycode still execute?
在 VB.NET 中,如果从 中返回一个值Catch,Finally代码还会执行吗?
For instance (I've generalized this code a bit):
例如(我已经概括了这段代码):
Try
response = Client.doRequest()
Catch ex As Exception
'Request threw an error - Fatal failure.
InsertErrorLog(ex)
Return False
Finally
DisposeClient()
End Try
I need to ensure that DisposeClient()is executed all of the time. Because I am returning out of the Catch, will the Finallystill be executed?
我需要确保DisposeClient()一直执行。因为我是从 返回的Catch,还会Finally被执行吗?
回答by ichan-akira
Finallyblock is always executed, regardless of code execution going to Catchblock or not.
Finallyblock 总是被执行,不管代码执行是否会Catch阻塞。
Refer to: https://msdn.microsoft.com/en-us/library/fk6t46tz.aspx
请参考:https: //msdn.microsoft.com/en-us/library/fk6t46tz.aspx
Try it, using this code:
尝试一下,使用以下代码:
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
It displays message:
它显示消息:
Catch
and then
进而
E
This means, Finallyblock is always executed even the function do return at Catchblock.
这意味着,Finally即使函数在Catch块处返回,块也总是被执行。
回答by Virtual Anomaly
On closer inspection to the Microsoft MSDN docs, I notice:
在仔细检查 Microsoft MSDN 文档时,我注意到:
Control is passed to the Finallyblock regardless of how the Try...Catchblock exits.
The code in a Finallyblock runs even if your code encounters a Returnstatement in a Tryor Catchblock.
Control does not pass from a Tryor Catchblock to the corresponding Finallyblock in the following cases:
- An EndStatement is encountered in the Tryor Catchblock.
- A StackOverflowExceptionis thrown in the Tryor Catchblock.
控制被传递到最后阻挡,无论怎样的 尝试...赶上块退出。
在代码最后块运行,即使您的代码遇到一个返回语句在尝试或赶上块。
在以下情况下,控制不会从Try或Catch块传递到相应的 finally块:
- 一个结束语句在遇到尝试或赶上块。
- 一个StackOverflowException在抛出尝试或赶上块。
In short, yes - the Finallyis always executed in mostcases.
简而言之,是的 -最后总是在大多数情况下执行。

