Handling Exceptions with ASP.NET | 2 | WebReference

Handling Exceptions with ASP.NET | 2


[prev]

Try/Catch Blocks

You will notice throughout our application the use of try/catch blocks. Since we're working with handling exceptions, it's important to note that try/catch block(s) are the basic fundamental building base to handling exceptions. Anytime your application does the following operations, you should use them:

  • Connecting to a database.
  • Executing a query against a database, whether its select, update, delete or insert.
  • When checking for certain query string parameters, specifically guides

Build or Run-Time Errors

Another annoyance with building Web applications, or applications in general are build and run-time errors. The difference between them is subtle but important. A build error is when your application can't compile because of the following:

  • Incorrect variable declarations, or assigning a variable an incorrect data type.
  • References to DLL files.

A couple examples might include the following:

Scenario 1: In our default.aspx.cs file, if you look inside our page load event you will see the following:


namespace ExceptionHandling
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<ExceptionHandlingGetData> person = ExceptionHandlingGetData.GetParticipants();
            rpPerson.DataSource = person;
            rpPerson.DataBind();
        }
    }
}

As you can see from the above, we're casting a person object as a generic list so we can call its static method, and then binding that object to our repeater control. However, if we comment or take out the reference to the cast, leave the last two lines of code, and then build, you will get the following error message:

Handling Exceptions with ASP.NET

Scenario 2: Another type of build error that happens frequently for developers is when you create a variable with a data type of string but assign it a value of another data type. You might be thinking that's crazy, but it does happen. Examples in our application might include first and last name and email, which are all created as string variables. However, in our while loop, if you assign the object property to another data type, such as integer, you will receive a build error as shown below:

Handling Exceptions with ASP.NET

A run-time error occurs when your application encounters an exception that a developer didn't anticipate. It's different because you can build (compile) your solution, but once you hit the exception, your application is non-responsive and your user can't complete the tasks they need. An example of this occurs when viewing our participant's detailed information. Our default.aspx page shows the number of people in our database, but our viewentry.aspx will show detailed information for each participant.

From the project downloads section, take a look at viewentry.aspx. In the file you will see the following:

  • Two place holder controls, with the following:
    • First one contains our form for showing existing entries via our query string.
    • Second place holder contains a failure message.

From the solution explorer, do the following:

  • Left click the plus (+) sign next to viewentry.aspx.
  • Double click viewentry.aspx.

In this file you will see the following:

  • In page load, a try catch block which checks to see if a query string with a parameter of guide is supplied:
    • If it IS, we query our data.
    • If it IS NOT, we catch the exception, and show our failure place holder message.

With this in place, you can successfully prevent a run-time error from occurring. If you want to see the run-time error occur, simply comment out the try/catch and run the application.

Incorrectly Supplying Parameters to a Stored Procedure

Another common type of exception error developers run across is when working with stored procedures through application logic. For example, our view entry page passes a query string so we can view individual participants and update their information. Once we collect their information, we call an update method and supply our stored procedure. However, if we forget to do that, we'll get a run time error. To reproduce, do the following from the solution explorer:

  • Left click the plus (+) sign next to classes.
  • Double click ExceptionHandlingActions.cs.

Between lines 30-33, if you were to comment out one of those parameters (@FName), run the solution, and then try and update one of the participants, you will get the following run-time error:

Handling Exceptions with ASP.NET

Handing Exceptions Gracefully for the Visitor, While Supplying Enough Information to the Developer

We have come to one of the most useful features of ASP.NET 2.0 and above. While we have uncovered many types of exceptions that can occur in an application, a developer's ability to predict all of them is simply impossible. With ASP.NET 2.0 and above, we can configure our configuration file to show a custom error message to our user, while allowing us to view the specific details of the error, which is great for both parties involved. From the solution explorer, do the following:

  • Double click web.config.

Inside system.web, add the following:


<customErrors mode="RemoteOnly" defaultRedirect="error.htm" />

As you can see from the code above, we added a custom errors tag, with the following properties:

  • Mode: can be On, Off, RemoteOnly
    • On: Means custom errors will show.
    • Off: Means everyone will receive detailed error messages.
    • Remote only: Means end users will receive our custom page, and developers will receive the detailed error message.
  • defaultRedirect: error.htm: This page is our custom error page. It can be any Web page you want.

In order to test this, you will need to cause a run-time error on a Web server.

Summary

In this article you learned how to work with and handle exceptions. Furthermore, you learned the following:

  • How to diagnose and correct database connection issues with your application.
  • Use of try/catch blocks through applications when you are connecting to a database or executing queries.
  • Difference between a build and run-time error.
  • How to use a try/catch block to handle query strings that are not passed through the URL.
  • How to identify when you haven't supplied a parameter to a stored procedure in the application.
  • How to gracefully show users a custom error message from a Web page, while allowing developers the ability to see the detailed error message.

Code Download

  • Exception handling application source code
  • About the Author

    Ryan Butler is the founder of Midwest Web Design. His skill sets include HTML, CSS, Flash, JavaScript, ASP.NET, PHP and database technologies.

    Original: Apr. 11, 2011


    [prev]