21.5. Executing a Statement, Finally

Another block in the Try...End Try sequence, Finally, is handy for cleaning up operations. For example, if the code opens a data connection successfully but another statement throws an exception, Finally can tidy up and close the connection. It's not a full recovery; however, it reduces the exception's collateral damage.

In Listing 21-3, the Try block includes a Throw statement to cause an error programmatically (and to illustrate how to create and raise custom exceptions). A Catch statement catches the deliberate exception immediately and puts the error object into its own variable, ex. The lblErr.Text = ex.Message line displays the error message on-screen.

To show that the Finally statement is executing, the code inside the Finally block adds its text to the existing message.

Listing 21-3. Throwing, Catching, and Finally
Protected Sub Page_Load _
(ByVal sender As Object, ByVal e As System.EventArgs)
    Try
        Throw (New Exception("A custom exception!"))
    Catch ex As Exception
        lblErr.Text = ex.Message
    Finally
        lblErr.Text = lblErr.Text & "<br>Finally executed."
    End Try
End Sub

People like to say that Finally executes, no matter what. This list of conditions shows that's not quite true:

  • Try block runs without error: Finally block executes.

  • Exception thrown in Try block and caught in a Catch block: Finally block executes.

  • Exception thrown in Try block, caught in Catch block, and rethrown in Catch block: Finally block doesn't execute.

  • Exception thrown ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.