The FileExists function presented earlier in this chapter uses the Resume statement within the error handler to rerun the statement that originally caused the error, and it uses the Resume Next statement to run the statement following the statement at which the error occurred.
You can use one of a number of statements to exit an error handler. The statement you use on any given occasion depends on the circumstances, as explained in the following table.
Statement |
Description |
Resume Next |
Resumes execution at the statement immediately following the one that caused the error. Use this statement to skip over the statement that caused the error. |
Resume |
Resumes execution at the statement that caused the error. Use this statement to repeat an operation after you've corrected the error. |
Resume line |
Resumes execution at the label specified by line, where line is a nonzero line number or line label that's in the same procedure as the error handler. Because jumping to specific line numbers results in unstructured code, using this statement isn't recommended. |
Error Err |
Triggers the most recent run-time error again. When this statement is run within the error handler, Visual Basic searches the calls list for another error handler. |
The preceding table assumes that the error occurred in the same procedure as the error handler. If this isn't the case, Visual Basic searches the procedures in the calls list for another error handler. For more information about this situation, see the following section, "Handling Unanticipated Errors."
The following illustration shows how the Resume and Resume Next statements differ.
Generally, you use Resume whenever the user must correct the situation that caused the error before program execution can continue. Use Resume Next whenever a correction by the user isn't required, and you want to continue program execution without trying again to run the statement that caused the error. With Resume Next, you can write an error handler that never reveals run-time errors to the user.
For example, the following function uses an error handler to perform "safe" division on its arguments without revealing errors that might occur. Null is returned if errors do occur.
Function Divide(numer, denom) Const ERR_DIV0 = 11, ERR_OVERFLOW = 6, ERR_ILLFUNC = 5 On Error GoTo MathHandler Divide = numer / denom Exit Function MathHandler: If Err = ERR_DIV0 Or Err = ERR_OVERFLOW Or Err = ERR_ILLFUNC Then Divide = Null ' If error was Division by zero, Overflow, ' or Illegal function call, return Null. Else MsgBox "Unanticipated error " & Err & ": " & Error, _
vbExclamation Divide = Null End If ' In all cases, Resume Next continues Resume Next ' execution at the Exit Function statement.
End Function