This example of error handling uses two functions:
handler |
the function which handles errors |
thrower |
the function which potentially throws errors |
The script fragment is as follows:
# a function which may throw an error
#
(defun Integer thrower ( (n Integer) )
(if (< n 0)
# yes indeedy...throw that error!
(throw (create Error 100 1 "I don't like negative numbers"))
# otherwise, check for large numbers
(if (> n 1000)
(throw (create Error 101 2 "I don't like large numbers"))
# otherwise, all is well
(printAux "Thankyou.... I like the number " n "\n")
)
)
(return n)
)
# the function which handles errors
#
(defun NIL handler ( (n Integer) )
(local (err Error) # required since we catch errors here
)
(try
(do
(printAux "the number is " n "\n")
# call the function which might throw an error
(thrower n)
(printAux "...well...we survived!\n")
)
# we know that the function 'dangerous' may throw errors
# with errorClass = 100
#
(catch 100
(printAux "CAUGHT: the following error: " err.string)
)
)
(return ())
)
handler catches errors, it must (and indeed has!)
the local variable called err
of type Error defined. If this variable is not defined,
the very act of catching an error will itself cause an error...not exactly a
good idea.
thrower throws
an error with class of 100. This is caught by the handler
function.
thrower throws
an error with class of 101. This is not caught by the handler
function -- it may be caught by a function which calls handler.
handler is given a negative number, it does not print out
the text ...well...we survived!. However, since the error is caught,
it does print out the text CAUGHT: the following error.
handler is given a number > 1000, it does not print out
the text ...well...we survived!. Further, since the error is not caught,
it does not print out the text CAUGHT: the following error.
| Contents | Index | Current topic: objects | Related topics: functions |