HomeHome   About ScottAbout Scott   FacebookFacebook   TwitterTwitter   Email NewsletterNewsletter   RSS FeedRSS Feed

It’s inevitable that you’ll generate an error or two (or three, or four…) when you code in Classic ASP. I’ll show you how to trap errors and use them to your advantage.

Before working with the Err Object, it’s helpful to know its properties:

Property Description Example
Number Error number for the most recent error (helpful for trapping) 7
Description String containing a description of the error Division by 0
Source Source of an error, such as an object or application Project.class

Code Snytax

First, discover if Err.Number is greater than 0.

If Err.Number > 0 Then
'Place error handling code here, such as description and custom message
End If

Here is an instance of attempting to access a subscript of an array that is out of range, making it invalid:

myArr = Array(“one”,”two”,”three”)
Response.Write(“Element #3 is ” & myArr(3) & ”
“)

The result that shows up in your browser window is fairly cold and technical, and doesn’t adequately describe to some people what the problem is:

Microsoft VBScript runtime error '800a0009'

Subscript out of range: ‘[number: 3]’

/login.asp, line 110

We can do better than this. By trapping this error, we can print out a much easier-to-read error message.

myArr = Array("one","two","three")
Response.Write("Element #3 is " & myArr(3) & "
")

If Err.Number > 0 Then
Response.Write(“Error #” & Err.Number & ”
“)
Response.Write(“Error Source: ” & Err.Source & ”
“)
Response.Write(“Error Description: ” & Err.Description & ”
“)
End If

And here is its output:

Error #7
Error Source: Microsoft VBScript runtime error
Error Description: Subscript out of range

This result, although only tweaked a small bit from the first example, is much simpler to understand. Use these custom error messages whenever you want to help explain the error to yourself or wish to report an error in a nicer fashion to your users. And if you really want to make this more “user-friendly”, you can add the custom layout of your website (especially if you have all your repeated page elements in .inc files) to replace the bland, featureless, white pages that normally appear on your browser when an error occurs.

Using the Err Object to Trap Errors in Classic ASP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.