Windows Dev Center

Handling Errors in VBScript

There is little difference between the methods used in Visual Basic and those used with VBScript. The primary difference is that VBScript does not support the concept of error handling by continuing execution at a label. In other words, you cannot use On Error GoTo in VBScript. Instead, use On Error Resume Next and then check both Err.Number and the Count property of the Errors collection, as shown in the following example:

<!-- BeginErrorExampleVBS -->
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE>Error Handling Example (VBScript)</TITLE>
</HEAD>
<BODY>

<h1>Error Handling Example (VBScript)</h1>

<%

   Dim cnn1
   Dim errLoop
   Dim strError

   On Error Resume Next
      
   ' Intentionally trigger an error.
   Set cnn1 = Server.CreateObject("ADODB.Connection")
   cnn1.Open "nothing"

   If cnn1.Errors.Count > 0 Then
      ' Enumerate Errors collection and display
      ' properties of each Error object.
      For Each errLoop In cnn1.Errors
         strError = "Error #" & errLoop.Number & "<br>" & _
            "   " & errLoop.Description & "<br>" & _
            "   (Source: " & errLoop.Source & ")" & "<br>" & _
            "   (SQL State: " & errLoop.SQLState & ")" & "<br>" & _
            "   (NativeError: " & errLoop.NativeError & ")" & "<br>"
         If errLoop.HelpFile = "" Then
            strError = strError & _
               "   No Help file available" & _
               "<br><br>"
         Else
            strError = strError & _
               "   (HelpFile: " & errLoop.HelpFile & ")" & "<br>" & _
               "   (HelpContext: " & errLoop.HelpContext & ")" & _
               "<br><br>"
         End If
                  

         Response.Write("<p>" & strError & "</p>")
      Next
   End If

%>

</BODY>
</HTML>
<!-- EndErrorExampleVBS -->
Show:
© 2015 Microsoft