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

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.