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.4. Using Try...Catch in Risky Situations

Sometimes you sense that your code is getting into a risky situation — usually when your routines depend on something external, such as the existence of a file, a directory, or data connection. Instead of relying on a global error handler, deal with the exception locally.

In this example, you use a Try...Catch block to wrap code that might throw an exception. Additionally, you're quite specific about the exceptions that you're willing to handle locally. Note: This example assumes that you are not using the Global.asax file to handle application errors.

To catch and report specific exceptions, follow these steps:

  1. Add an ASP.NET Gridview control to a page.

  2. Add a Label control with an ID of lblError to the page.

    As shown in Figure 21-4, the Label provides feedback to the user in case something goes wrong.

    Figure 21-4. Ready to display the filenames.
  3. In Source view, add <%@ Import Namespace="System.Linq" %> to the top of the .aspx page for LINQ query support.

  4. In Source view, use Listing 21-2 as the handler for the Page object's Load event.

Listing 21-2. Catching and Reporting Specific Exceptions
Protected Sub Page_Load (ByVal sender As Object, _
  ByVal e As System.EventArgs)

  Try                                                                         →4 Dim q = From FileName In _ System.IO.Directory.GetFiles _ ("c:\doesntexist\", "*.*", _ System.IO.SearchOption.AllDirectories) GridView1.DataSource = q GridView1.DataBind() ...
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