Go to: Articles List

Trapping Errors with the Err Object

Undoubtedly in your code writing experience you will generate an error or two (maybe more). In this How To I will explain how to trap errors and use them to your advantage. First a little about the Err Object.

Err Object Properties
Number Number of the error generated (helpful to know for trapping)
Description Description of the error
Source The object or application that was the source of the error
HelpContext Context ID for the help file topic
HelpFile File and path to help file

Syntax:

Check to see that Err.Number is greater than 0.

If Err.Number > 0 Then
     'Some error handling code (print out #, description, custom message, etc.)
End If

Here is an example of trying to access a subscript of an array that is out of range (invalid).

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

Result:

Microsoft VBScript runtime error '800a0009'

Subscript out of range: '[number: 3]'

/test.asp, line 8

Not very nice is it? We can trap this error and print out a nice error message.

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

If Err.Number > 0 Then
     Response.Write("Error #" & Err.Number & "<br>")
     Response.Write("Error Source: " & Err.Source & "<br>")
     Response.Write("Error Description: " & Err.Description & "<br>")
End If

Result:

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

The result is much easier to read. You can apply this to any code that you write. If you are generating an error and don't like what you are getting back, you can add the above code to help explain the error to you or report an error nicely to your users.