Trapping Program Errors

advertisement
Trapping Program Errors
• Errors may be trapped asynchronously
• Visual Basic generates an error number
whenever an error occurs
• To handle errors, you must
– Turn on error handling feature: On
Error...
– Create error handling code
– Determine what is to be done after
processing the error (continue, end
program,…)
• Place On Error in any procedure that is to
traps and processes errors
• Example:
– Private Sub Form_Load()
– On Error GoTo HandleErrors
'Turn on
error trapping
– Open "A:\Testdata.dat" For Input As #1
– … (more code here)
– Exit Sub 'exit to avoid executing error
routine
– HandleErrors:
– ‘some code to handle error
– Resume
– End Sub
• A line label is a name followed by a
colon on a line by itself
• HandleErrors is a line label
• Forms of On Error statement:
– On Error GoTo linelabel transfer control to
label in module
– On Error Resume Next skip error line &
continue with next
– On Error GoTo 0
handling
turns off error
The Err Object
• The Err object holds information about
error that just occurred
• Err.Source holds the source of the error
• Err.Number holds the error number
• Err.Description contains error
description
• You can raise an error condition—turn
on an error—with: Err.Raise Number:=xx
• Err.Number
– 7
– 9
– 11
– 13
– 52
– 53
– 54
– 58
– 61
– 67
– 68
– 70
– 71
– 75
– 76
– 482
Err.Description
Out of memory
Subscript out of range
Division by zero
Type mismatch
Bad filename or number
File not found (fnf)
Bad file mode
File already exists
Disk full
Too many files
Device unavailable
Permission denied
Disk not ready
Path/file access error
Path not found
Printer error
• Raise error 76 in program code: Err.Raise
Number:=76
Coding Error-Handling Routines
• On Error statement designates error
handler
• Code to handle errors follows line label
• Line label appears on line by itself and
ends with a colon
• A Case statement works well to sort out
errors with a "switchboard"
• Continue execution with Resume
statement
• Using Case to handle errors with a
"Switchboard":
–
–
–
–
–
–
Select Case Err.Number
Case 53
'Handle error # 53 here
…
Case 71
'Handle error # 71 here
...
Case Else 'Handle all other errors
here
–
…
– End Select
• Resume statement forms:
– Resume
continues with line causing
error (careful!)
– Resume Next
continues with line
following one that caused error
– Resume linelabel continues at line label,
which must be in same proc
• Exit statement jumps out of structure--a
function, subroutine, or loop
• Exit should be placed before line label
of error handling routine so normal
program flow doesn't drop through the
error code.
Download