Contact me if you'd
like to advertise
in this prime spot
 CoverYourASP --> Handling exceptions when opening database --> Part 2

Free membership

Join in the fun! Sign in
Member Services

Site navigation
Download the entire site!
Search my articles
Free Magazines
Browse the directory

Send me feedback
Buy my boxer shorts

Recommend this page
Printer-friendly page

Resources I recommend
Link to my site
Advertising slashed!
About your privacy
Legal stuff
Site statistics
54 active users
1918 visitors today
2048 pages today
(only part of today)
Tools I use

CoverYourASP
Copyright © 1999-2009 James Shaw.
All rights reserved.

ASP.NET Blog
RSS submissions
E-commerce

Now open source with SourceForge!

Trapping the exception

Most errors on the site get handled by the server (IIS) calling the HTTP 500 error handler. In other words, I don't do anything to stop the error, I just let the server stop executing the offending page, and display an error. My handler just displays a prettier error.

Exception handling is different. Now I'm providing code to execute when an error occurs, and depending on the error I can do different things. Try again, stop the script, even send an HTML <form> to the user asking him a question.

The try...catch block

Exception handling is very easy to implement. Here is the code that traps exceptions caught when opening a connection to my database:

try
{
   // open the database, catching any errors that occur
   oConnection.Open( sConnectionString );
}
catch ( e )
{
   // display error message, and send email
   DatabaseException ( e );

   // quit running the script completely
   Response.End ( );
}

If any error occurs anywhere between the braces of the try block, then execution will immediately continue with the first statement inside the catch block. A lot of errors can be caught in this way - errors raised by COM components such as the ADODB.Connection shown here, but also arithmetic errors such as divide by zero.

In the above example, I'm doing two things in my catch block. I display an error message by calling a function that I'll discuss in a minute, then I stop the script running by calling Response.End (there's little point in continuing if the connection fails).

But, back to the function call I made - note that I pass in the variable e that was specified in the catch statement.

Part 3: But what is "e"?...

Featured sponsor
My favorite resources

Tiki Statues - Tiki Masks - Tiki Totems



I share my content

Supporting ASPRSS

Do you need a quick and easy way to link to my articles? All the information you need is published with ASPRSS...


New Proposal Kit Professional 5.1
Brand yourself as a top professional: create quotes and amazing proposals and get many legal documents free!

The latter saved me 3 times the purchase price on the first day I owned it!