Database Programming Techniques > Handling Database Errors > Trapping errors |
Trapping an error is the first step in handling an error. As an example, suppose there is a grid bound to a Data control, displaying a Recordset with a numeric field. Suppose also that a user enters non-numeric data in the grid column associated with the numeric field. When an attempt is made to change rows, the Data control automatically initiates the update process and tries to store the non-numeric data, resulting in an error.
How is this error to be handled? Will the error appear as a trappable error, or in an error event? The answer lies with the first key point given. The error will be reported by the control or code which initiates the row change (the source of the operation which ultimately leads to the error), since it is the row change operation which cannot be completed.
How many ways can you initiate the row change operation, and how is each trapped? Here are some examples:
Click a command button which performs a Recordset move operation. In this case, the row change operation is initiated by a line of Visual Basic code, and the error will be reported as a trappable error, which is handled with the On Error statement.
Click a button of the data control. In this case, there is no identifiable line of Visual Basic code which can be trapped, so the error will be reported in an error event. Because the row change is initiated by the data control, the data control's Error event will be fired.
Click any non-current row of True DBGrid. As in example 2, there is no identifiable line of Visual Basic code which can be trapped, so once again the error is reported in an error event. However, in this case, the row change is initiated by True DBGrid, so the error is reported in the grid's Error event.
Press the down arrow key. As in example 3, the error is reported in the grid's Error event for the same reasons.
Press the down arrow key, but perform a row change operation in the KeyDown event of the grid using a bookmark or Recordset move operation. In this case, the row change event is initiated by the code in the KeyDown event, and the error is trapped through the On Error statement.