;;; CONDITIONS 5: REPORTS, WARN, SIGNAL ;;; ;;; DEFINE-CONDITION (exercise 3) names a condition class; the ;;; :REPORT option gives it the text humans see - and PRINC of the ;;; condition prints that text. ;;; ;;; ERROR unwinds to the debugger. WARN reports and CARRIES ON - it ;;; signals a WARNING, catchable like anything else. SIGNAL is the ;;; bare mechanism: handlers see it, nobody else is bothered. (define-condition low-battery (condition) ()) ;; TODO: A condition of your own, EMPTY-CART - a subclass of ERROR ;; with :report "The cart is empty - nothing to check out." - and ;; CHECKOUT signals it when ITEMS is NIL. (define-condition empty-cart (error) ()) (defun checkout (items) (when (null items) (error 'empty-cart)) (list 'order items)) ;; TODO: BATTERY-CHECK warns "battery ~a%!" when PERCENT is under ;; 20 - and returns (list 'battery percent) either way. (defun battery-check (percent) (error "battery ~a%!" percent) (list 'battery percent)) ;; TODO: CHECK-BATTERY signals LOW-BATTERY when PERCENT is at or ;; under 10 - a plain condition, not an error - then returns ;; (list 'battery percent). (defun check-battery (percent) (error "low battery") (list 'battery percent)) ;;; ------------------------------------------------------------------ ;;; Checks. Read them - they tell you what to aim for - but leave ;;; them unchanged. ;;; ------------------------------------------------------------------ (check-equal '(order (milk)) (checkout '(milk))) (check-error (checkout '()) 'empty-cart) (check-equal "The cart is empty - nothing to check out." (handler-case (checkout '()) (empty-cart (c) (format nil "~a" c)))) (check-equal '(battery 15) (battery-check 15)) (check-equal '(battery 90) (battery-check 90)) (check-equal :noticed (handler-case (battery-check 15) (warning () :noticed))) (check-equal :noticed (handler-case (warn "battery low") (warning () :noticed))) (check-equal :swapped (handler-case (check-battery 5) (low-battery () :swapped))) (check-equal '(battery 20) (check-battery 20)) (check-equal :swapped (handler-case (check-battery 10) (low-battery () :swapped))) (check-equal '(battery 11) (handler-case (check-battery 11) (low-battery () :leaked)))