Errors caused by AutoLISP functions can result in a program ending unexpectedly, make sure to handle all known situations that could cause an error.
The following defines a function named catch-me-if-you-can. This function accepts two number arguments and uses vl-catch-all-apply to divide the first number by the second number. The vl-catch-all-error-p function determines whether the return value from vl-catch-all-apply is an error object. If the return value is an error object, catch-me-if-you-can invokes vl-catch-all-error-message to obtain the message from the error object.
(defun catch-me-if-you-can (dividend divisor / errobj) (setq errobj (vl-catch-all-apply '/ (list dividend divisor))) (if (vl-catch-all-error-p errobj) (progn (print (strcat "An error occurred: " (vl-catch-all-error-message errobj))) (initget "Yes No") (setq ans (getkword "Do you want to continue? [Y/N]: ")) (if (equal (strcase ans) "YES") (print "Okay, I'll keep going") ) ) (print errobj) ) (princ) )
(catch-me-if-you-can 50 2)
(catch-me-if-you-can 50 0)
"An error occurred: divide by zero" Do you want to continue? [Y/N]:
If you enter y (or yes), catch-me-if-you-can indicates that it will continue processing. Try modifying this example by changing vl-catch-all-apply to apply. Load and run the example with a divide by zero again. When apply results in an error, execution immediately halts and *error* is called, resulting in an error message.
The vl-catch-* functions are especially important when you use ActiveX with AutoLISP. Many of the AutoCAD ActiveX automation methods are designed to be used in the “programming by exception” style. This means they either return useful values if they succeed, or raise an exception if they fail (instead of returning an error value). If your program uses ActiveX methods, you must prepare it to catch exceptions, otherwise the program halts, leaving the user at a Command prompt.