Data Access  «Prev  Next»

Lesson 9 Defensive programming: handling errors
Objective Include general error-handling code in an asp page.

Defensive Programming - Handling Errors

There is a chance that your Web application will have an occasional error. Regardless of the quality of the application, there are other factors that can cause things to go awry, such as database web applications. You should plan for this possibility and include some level of error handling in the application.
Handling errors in database-centered Web applications is really no different than handling errors in other types of applications. You just try to anticipate what could go wrong and add the necessary programming logic to catch and handle the error.

Types of errors

Typical database-related errors you should plan for include:
  1. Failures to connect to a database
  2. Failures to open a database
  3. Failed query

Sources of error problems

Errors can result from any of the following:
  1. Network problem
  2. Hardware problem
  3. Security or administrative problem
  4. Number of users already accessing the system
  5. Corrupted database

Avoiding errors

The scripting language you are using should have error-handling capability. For example, Visual Basic Script has the On Error Resume Next statement , and JavaScript has the try-catch statement. These can be used to respond in some manner to an error condition. The ToolTip below shows how the VBScript On Error Resume Next statement is used to trap an error condition.
src="images/onerror_010mo.gif" width="404" height="305" alt="Apply, Filter, Sort">
  1. The On Error Resume Next statement tells VBScript to resume program execution on the line immediately following the one where the error occurred. Without this, the program would just crash. If an error occurs on any line following this statement, then VBScript will continue with the next program statement.
  2. When a runtime error occurs, information about the error is stored in the VBScript Err object. You can use this information in conjunction with the On Error Resume Next statement to handle error conditions intelligently. In this example, error handler code is passed information about the error.
  3. This function is called when the Err object's number property does not equal zero, which indicates an error. This example simply displays information about the error. You can write much more sophisticated code to take some action, depending on the error
Handling Errors Using VBScript
The On Error Resume Next statement does not do anything about the error. Instead, it keeps the program from crashing.
Remember, handling the error is still the programmer's responsibility. The next lesson wraps up the module and concludes with a quiz.