Exceptions: Difference between revisions
Content added Content deleted
(some "exceptions" using Common Lisp conditions) |
|||
Line 298: | Line 298: | ||
</cfcatch> |
</cfcatch> |
||
</cftry> |
</cftry> |
||
=={{header|Common Lisp}}== |
|||
The Common Lisp condition system allows much more control over condition signaling and condition handling than many exception-based systems. The following example, however, simply defines a condition type, <code>unexpected-odd-number</code>, defines a function <code>get-number</code> which generates a random number, returning it if it is even, but signaling an <code>unexpected-odd-number</code> condition if it is odd. The function <code>get-even-number</code> uses <code>[http://www.lispworks.com/documentation/HyperSpec/Body/m_hand_1.htm handler-case]</code> to call <code>get-number</code> returning its result if no condition is signaled, and, in the case that an <code>unexpected-odd-number</code> condition is signaled, returning one plus the odd number. |
|||
<lang lisp>(define-condition unexpected-odd-number (error) |
|||
((number :reader number :initarg :number)) |
|||
(:report (lambda (condition stream) |
|||
(format stream "Unexpected odd number: ~w." |
|||
(number condition))))) |
|||
(defun get-number (&aux (n (random 100))) |
|||
(if (not (oddp n)) n |
|||
(error 'unexpected-odd-number :number n))) |
|||
(defun get-even-number () |
|||
(handler-case (get-number) |
|||
(unexpected-odd-number (condition) |
|||
(1+ (number condition)))))</lang> |
|||
A good introduction to Lisp's condition system is the chapter [http://gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html Beyond Exception Handling: Conditions and Restarts] from Peter Seibel's [http://gigamonkeys.com/book/ Practical Common Lisp]. |
|||
=={{header|D}}== |
=={{header|D}}== |