diff 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 diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/clojure/contrib/test_contrib/condition/example.clj	Sat Aug 21 06:25:44 2010 -0400
     1.3 @@ -0,0 +1,66 @@
     1.4 +;;  Copyright (c) Stephen C. Gilardi. All rights reserved.  The use and
     1.5 +;;  distribution terms for this software are covered by the Eclipse Public
     1.6 +;;  License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
     1.7 +;;  be found in the file epl-v10.html at the root of this distribution.  By
     1.8 +;;  using this software in any fashion, you are agreeing to be bound by the
     1.9 +;;  terms of this license.  You must not remove this notice, or any other,
    1.10 +;;  from this software.
    1.11 +;;
    1.12 +;;  clojure.contrib.condition.example.clj
    1.13 +;;
    1.14 +;;  scgilardi (gmail)
    1.15 +;;  Created 09 June 2009
    1.16 +
    1.17 +(ns clojure.contrib.condition.example
    1.18 +  (:use (clojure.contrib
    1.19 +         [condition
    1.20 +          :only (handler-case print-stack-trace raise *condition*)])))
    1.21 +
    1.22 +(defn func [x y]
    1.23 +  "Raises an exception if x is negative"
    1.24 +  (when (neg? x)
    1.25 +    (raise :type :illegal-argument :arg 'x :value x))
    1.26 +  (+ x y))
    1.27 +
    1.28 +(defn main
    1.29 +  []
    1.30 +  
    1.31 +  ;; simple handler
    1.32 +  
    1.33 +  (handler-case :type
    1.34 +    (println (func 3 4))
    1.35 +    (println (func -5 10))
    1.36 +    (handle :illegal-argument
    1.37 +            (print-stack-trace *condition*))
    1.38 +    (println 3))
    1.39 +
    1.40 +  ;; multiple handlers
    1.41 +  
    1.42 +  (handler-case :type
    1.43 +    (println (func 4 1))
    1.44 +    (println (func -3 22))
    1.45 +    (handle :overflow
    1.46 +      (print-stack-trace *condition*))
    1.47 +    (handle :illegal-argument
    1.48 +      (print-stack-trace *condition*)))
    1.49 +
    1.50 +  ;; nested handlers
    1.51 +
    1.52 +  (handler-case :type
    1.53 +    (handler-case :type
    1.54 +      nil
    1.55 +      nil
    1.56 +      (println 1)
    1.57 +      (println 2)
    1.58 +      (println 3)
    1.59 +      (println (func 8 2))
    1.60 +      (println (func -6 17))
    1.61 +      ;; no handler for :illegal-argument
    1.62 +      (handle :overflow
    1.63 +        (println "nested")
    1.64 +        (print-stack-trace *condition*)))
    1.65 +    (println (func 3 4))
    1.66 +    (println (func -5 10))
    1.67 +    (handle :illegal-argument
    1.68 +      (println "outer")
    1.69 +      (print-stack-trace *condition*))))