exceptioncommon-lispconditional-statementsrestartcondition-system

common lisp exception handling (condition and restart)


I have been read the common lisp "Practical Common Lisp" exception handling chapter for days, but I am now so confused with the samples and the explanations, in the meanwhile I tried to write some testing sample, but it didn't work as I expected, below is my testing samples.

  1. Condition definition

    (define-condition evenp-error (error) 
      ((text :initarg :text :reader text)))
    
  2. Define function that prints odd number

    (defun filter-evenp (lst)
      (dolist (x lst)
        (if (not (evenp x)) 
          (print x)
          (error 'evenp-error :text x))))
    
  3. Restart function

    (defun skip-evenp (c) (invoke-start 'skip-evenp))
    
  4. Restart case

    (restart-case (filter-evenp (list 1 2 3 4 5))
      (skip-evenp () nil))
    

All I want to do is to print all odd numbers and skip the even errors, what is wrong with my sample? anybody help? many thanks in advance!!


Solution

  • You need to put your RESTART-CASE to where you want to restart the execution at:

    (defun filter-evenp (lst)
      (dolist (x lst)
        (restart-case
            (if (not (evenp x))
                (print x)
                (error 'evenp-error :text x))
          (skip-evenp () nil))))
    

    Then you should use HANDLER-BIND to handle the error:

    (handler-bind ((evenp-error #'skip-evenp))
      (filter-evenp (list 1 2 3 4 5)))