view src/clojure/contrib/test_contrib/condition/example.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line source
1 ;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and
2 ;; distribution terms for this software are covered by the Eclipse Public
3 ;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
4 ;; be found in the file epl-v10.html at the root of this distribution. By
5 ;; using this software in any fashion, you are agreeing to be bound by the
6 ;; terms of this license. You must not remove this notice, or any other,
7 ;; from this software.
8 ;;
9 ;; clojure.contrib.condition.example.clj
10 ;;
11 ;; scgilardi (gmail)
12 ;; Created 09 June 2009
14 (ns clojure.contrib.condition.example
15 (:use (clojure.contrib
16 [condition
17 :only (handler-case print-stack-trace raise *condition*)])))
19 (defn func [x y]
20 "Raises an exception if x is negative"
21 (when (neg? x)
22 (raise :type :illegal-argument :arg 'x :value x))
23 (+ x y))
25 (defn main
26 []
28 ;; simple handler
30 (handler-case :type
31 (println (func 3 4))
32 (println (func -5 10))
33 (handle :illegal-argument
34 (print-stack-trace *condition*))
35 (println 3))
37 ;; multiple handlers
39 (handler-case :type
40 (println (func 4 1))
41 (println (func -3 22))
42 (handle :overflow
43 (print-stack-trace *condition*))
44 (handle :illegal-argument
45 (print-stack-trace *condition*)))
47 ;; nested handlers
49 (handler-case :type
50 (handler-case :type
51 nil
52 nil
53 (println 1)
54 (println 2)
55 (println 3)
56 (println (func 8 2))
57 (println (func -6 17))
58 ;; no handler for :illegal-argument
59 (handle :overflow
60 (println "nested")
61 (print-stack-trace *condition*)))
62 (println (func 3 4))
63 (println (func -5 10))
64 (handle :illegal-argument
65 (println "outer")
66 (print-stack-trace *condition*))))