Skip to content

Instantly share code, notes, and snippets.

@kurogelee
Created March 29, 2014 03:44
Show Gist options
  • Save kurogelee/9847955 to your computer and use it in GitHub Desktop.
Save kurogelee/9847955 to your computer and use it in GitHub Desktop.
ClojureでJava 7対応版のwith-open関数を作ってみる ref: http://qiita.com/kurogelee/items/dfb6c29bfec87ae6f744
(auto-close [c (reify java.lang.AutoCloseable
(close [this] (throw (java.io.IOException. "closeA"))))]
(throw (IllegalStateException. "tryB")))
(defmacro try-finally [main-form dispose-form]
`(with-local-vars [th# nil]
(try ~main-form
(catch Throwable t# (do (var-set th# t#) (throw t#)))
(finally
(try ~dispose-form
(catch Throwable t#
(if (nil? @th#) (throw t#) (do (.addSuppressed ^Throwable @th# t#) (throw @th#)))))))))
(defmacro auto-close [bindings & body]
{:pre[(vector? bindings)
(even? (count bindings))
(every? symbol? (take-nth 2 bindings))]}
(if (zero? (count bindings)) `(do ~@body)
`(let ~(subvec bindings 0 2)
(try-finally (auto-close ~(subvec bindings 2) ~@body)
(.close ~(bindings 0))))))
java.io.IOException: closeA
(Unknown Source) user/eval7216[fn]
(Unknown Source) user/eval7216
...
Exception in thread "main" java.lang.IllegalStateException: tryB
at trysample.TrySample.main(TrySample.java:6)
Suppressed: java.io.IOException: closeA
at trysample.TrySample.lambda$main$0(TrySample.java:5)
at trysample.TrySample$$Lambda$1/2536472.close(Unknown Source)
at trysample.TrySample.main(TrySample.java:7)
java.lang.IllegalStateException: tryB
(Unknown Source) user/eval7222
...
package trysample;
public class TrySample {
public static void main(String[] args) throws Exception{
try(AutoCloseable a = () -> {throw new java.io.IOException("closeA");}){
throw new IllegalStateException("tryB");
}
}
}
(with-open [c (reify java.lang.AutoCloseable
(close [this] (throw (java.io.IOException. "closeA"))))]
(throw (IllegalStateException. "tryB")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment