I am pretty new to programming in VB.Net, but I have been programming in other languages for a couple of decades now, including VB5/6 and C++.

When I am using a Try - Catch block to handle exceptions, what is the point of a Finally section? Wouldn't it be just the same as putting code after the End Try? So why use a Finally section because it looks like it just gets executed after everything else in the block, which is the same behaviour as code after the Try - Catch block.

Recommended Answers

All 4 Replies

Because the code in the Finally is always executed you might wonder what's the point. The point is that the code in the Finally block is logically associated with the code in the Try and Catch blocks. If you saw

Try
    'some statements
Catch ex As Exception
    'some more statements
End Try

'some other statements

You might (at some point) either be tempted to insert more code after the End Try, or move the code after the End Try somewhere else. However, if you saw

Try
    'some statements
Catch ex As Exception
    'some more statements
Finally
    'some other statements
End Try

you would know immediately that "some other statements" is associated with "some statements" and "some more statements". Typically, the Finally block contains cleanup code. For example, if, in the Try block, you opened one or more files, you'd want to close those files whether or not an exception occurs. Rather than duplicate this code in the Try and Catch blocks, you place it in the Finally block.

So if I understand this now, which could still be in doubt, as an example, I create an object in Try. Catch handles the errors and Finally is here I Dispose of the object, if it is not going to used afterward.

Try
    stmTesting = New IO.StreamReader(strFilename)

Catch ex AS IOException
    REM Could not open the file for some reason.
    ' Do whatever to try to recover.
Finally
    REM I am just checking if the file can be openned at this point.
    REM I don't need to read it now.
    If Not (stmTesting Is Nothing) Then
        stmTesting.Close
        stmTesting = Nothing
    End If
End Try

Is that the idea?

Nutster, you may find this article helpful: Click Here

The code placed under the "Finally" section can be viewed like an in-place method definition that will always be called before leaving the "Try-End Try" block.

Let's say in your IOException example, that you can not recover from the file error and need to return control to the calling procedure via an "Exit Sub", "Exit Function", or "Return" statement. The "Finally" code will execute before the return. You could accomplish the same thing without using the "Finally" section, but it keeps the logic all together and easier to maintain.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.