In VB.NET, if you return a value from the Catch
, will the Finally
code still execute?
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 Finally
still be executed?
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.
In visual basic, Try Catch statement is useful to handle unexpected or runtime exceptions which will occur during execution of the program. The Try-Catch statement will contain a Try block followed by one or more Catch blocks to handle different exceptions.
The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks.
The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.
Finally
block is always executed, regardless of code execution going to Catch
block or not.
Refer to: 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, Finally
block is always executed even the function do return at Catch
block.
On closer inspection to the Microsoft MSDN docs, I notice:
Control is passed to the Finally block regardless of how the Try...Catch block exits.
The code in a Finally block runs even if your code encounters a Return statement in a Try or Catch block.
Control does not pass from a Try or Catch block to the corresponding Finally block in the following cases:
- An End Statement is encountered in the Try or Catch block.
- A StackOverflowException is thrown in the Try or Catch block.
In short, yes - the Finally is always executed in most cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With