Skip to Content
ASP.NET 3.5 For Dummies®
book

ASP.NET 3.5 For Dummies®

by Ken Cox
February 2008
Intermediate to advanced
428 pages
8h 52m
English
For Dummies
Content preview from ASP.NET 3.5 For Dummies®

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ASP.NET 3.5 Unleashed

ASP.NET 3.5 Unleashed

Stephen Walther
ASP.NET 4 Unleashed

ASP.NET 4 Unleashed

Stephen Walther, Kevin Hoffman, Nate Dudek

Publisher Resources

ISBN: 9780470195925Purchase book