1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
'+
' error_handler.vbs
' Error handling test
' Usage: cscript /nologo error_handler.vbs
'
' v1.0-0 13-oct-2010 DTL Didier.Morandi at gmail dot com
'-
Option Explicit
dim obj_file, filename, filespec, status, severity
const for_reading = 1, for_appending = 8, fatal_error = 1, not_fatal = 0
on error resume next
'file object creation
wscript.echo "Creating file object"
set obj_file = createobject("scripting.filesystemobject")
call err_handler(fatal_error)
wscript.echo "File object successfully created." & vbcrlf
'let's ask for the full file name spec.
wscript.stdout.write "Enter full filename specification <RET>=end: "
filespec = wscript.stdin.readline
if filespec = "" then wscript.quit 0
'we open the file - if we fail, script stops
wscript.stdout.writeline "Opening file " & filespec
set filename = obj_file.opentextfile(filespec, for_reading, false)
call err_handler(fatal_error)
wscript.echo "File successfully opened for READING." & vbcrlf
'if file exists, we write into it, close it and exit
'we fail because file is opened in READ mode. Let's decide it's not a fatal error
wscript.echo "Writing into file (should trigger an error)"
filename.writeline "Hello World"
call err_handler(not_fatal)
'same for close, if it is already closed
wscript.echo "Closing file"
filename.close
call err_handler(not_fatal)
wscript.echo "Done."
wscript.quit 0
'--------------------------------------------------------------------
sub err_handler(severity)
status = err.number
if status <> 0 then
wscript.echo err.source
if severity = 0 then
wscript.echo "Error " & status & " - " & err.description
wscript.echo ""
err.clear
else
wscript.echo "Fatal Error " & status & " - " & err.description
wscript.echo "Abort."
wscript.quit 1
end if
end if
end sub |
Partager