11

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?

1
  • 4
    Move the caret to Finally and press F1. You can't avoid falling in the pit of success: "Control passes to the Finally block just before it passes out of the Try…Catch structure. This is true even if an exception occurs anywhere inside the Try structure". Only ask for help if F1 can't get the job done. Commented Feb 24, 2016 at 11:49

2 Answers 2

14

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.

0
1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.