I'm just starting to learn Clojure and struggling to extract Exception metadata. When I run this:
(try
(/ 1 0)
(catch Exception error (println error)))
I get an ArithmeticException, as expected. The stacktrace printed looks like this:
#error {
:cause Divide by zero
:via
[{:type java.lang.ArithmeticException
:message Divide by zero
:at [clojure.lang.Numbers divide Numbers.java 188]}]
:trace
[[clojure.lang.Numbers divide Numbers.java 188]
[clojure.lang.Numbers divide Numbers.java 3901]
...
]}
It looks like a map to me, so I tried to extract the value from :cause with (:cause error), but it evaluates to nil.
How can I do that?
UPDATE:
After digging a bit, I found that #error {...} is a java.lang.Throwable class, is that correct?
I tried using Java interop (.getCause error), but also returns nil. Turns out (.getMessage) error) does return "Divide by zero".
Are there other ways to get specific attributes from that class, other than .getMessage()?
Clojure has ex-message to retrieve the message from an exception and ex-cause to retrieve the cause -- if there is one. The printed display of #error is a bit misleading here because there actually is no "cause" in the exception (in the Java sense of .getCause) because there is no chained exception.
Another useful function is Throwable->map which turns the exception (all exceptions are java.lang.Throwable at their root) into a regular Clojure hash map on which you can perform all the regular operations:
user=> (ex-message (try (/ 1 0) (catch Exception e e)))
"Divide by zero"
user=> (keys (Throwable->map (try (/ 1 0) (catch Exception e e))))
(:via :trace :cause)
user=> (:cause (Throwable->map (try (/ 1 0) (catch Exception e e))))
"Divide by zero"
user=>
Related
I am trying to run a test that is expected to throw some exception.
throws? works fine but when I try to thrown-with-msg? it throws an exception. To test it I picked up lines from documentation
Code:
(deftest check-exception
(testing "If Exception is thrown"
(is (thrown-with-msg? java.lang.ArithmeticException #\"Divide by zero\" (/ 1 0)))))
Compilation Error:
Exception in thread "main" clojure.lang.LispReader$ReaderException: java.lang.RuntimeException: Unsupported character: \"Divide
The 3rd parameter that needs to be passed is a Regular Expression . How do I pass that?
The literal for a regexp in Clojure is #"... ". So the \ you are using there is wrong. If you want to have quotes inside the regexp literal, then you quote them like you did. E.g. #"\"Divide by zero\""
edit: The source of confusion (literally)
The source code actually contains this line in the doc string:
(is (thrown-with-msg? ArithmeticException #\"Divide by zero\"
(/ 1 0)))
But this is due to the need to quote the " within the doc comment as well. Looking just at the doc with e.g. doc in the REPL
user=> (require 'clojure.test)
user=> (doc clojure.test)
...
(is (thrown-with-msg? ArithmeticException #"Divide by zero"
(/ 1 0)))
...
shows the correct code.
Regex is passed as follows:
(deftest check-exception
(testing "If Exception is thrown"
(is (thrown-with-msg? java.lang.ArithmeticException #"^.*Divide by zero.*$" (/ 1 0)))))
I would like to wrap exception which has been thrown by system or user(does not matter) and force it to return some value.
I wrote macro for it but it does not work.
Macro:
(defmacro safe-fn
[form]
(try
`(do ~form)
(catch Throwable e
1)))
Usage: (safe-fn (throw (RuntimeException. "Try me!")))
Actual output: RuntimeException Try me! clojure-brave-and-true.core/eval2219 (form-init6122238559239237921.clj:1)
Desired output: 1
Macros are just functions that return code to be evaluated, so you could write safe-fn like this:
(defmacro safe-fn
[form]
`(try
~form
(catch Throwable ~'_
1)))
Example:
(safe-fn (throw (RuntimeException. "Try me!")))
;=> 1
See my answer to this question for more detail on macros, and specifically on using them to catch exceptions.
The macro with-exception-default from the Tupelo library does exactly what you want:
Default Value in Case of Exception
Sometimes you know an operation may result in an Exception, and you
would like to have the Exception converted into a default value. That
is when you need:
(with-exception-default default-val & body)
Evaluates body & returns its result. In the event of an exception the
specified default value is returned instead of the exception."
(with-exception-default 0
(Long/parseLong "12xy3"))
;=> 0
This feature is put to good use in tupelo.parse, where you will find
functions that work like this:
(parse-long "123") ; throws if parse error
;=> 123
(parse-long "1xy23" :default 666) ; returns default val if parse error
;=> 666
How can I test for a function that throws an expected exception? Here is the function that throws the exception:
(defn seq-of-maps?
"Tests for a sequence of maps, and throws a custom exception if not."
[s-o-m]
(if-not (seq? s-o-m)
(throw (IllegalArgumentException. "s-o-m is not a sequence"))
(if-not (map? (first s-o-m))
(throw (IllegalArgumentException. "s-o-m is not a sequence of maps."))
true)))
I want to design a test like the following in which an exception is thrown and caught and then compared. The following does not work:
(deftest test-seq-of-maps
(let [map1 {:key1 "val1"}
empv []
s-o-m (list {:key1 "val1"}{:key2 "val2"})
excp1 (try
(seq-of-maps? map1)
(catch Exception e (.getMessage e)))]
(is (seq-of-maps? s-o-m))
(is (not (= excp1 "s-o-m is not a sequence")))))
I am getting these errors:
Testing util.test.core
FAIL in (test-seq-of-maps) (core.clj:27)
expected: (not (= excp1 "s-o-m is not a sequence"))
actual: (not (not true))
Ran 2 tests containing 6 assertions.
1 failures, 0 errors.
Obviously, I am missing something about writing tests. I am having trouble figuring that out. My project was set up with lein new, and I am running the tests with lein test.
Thanks.
The last assertion in your test is incorrect; it should be (is (= excp1 "s-o-m is not a sequence")) since map1 isn't a seq of maps.
Aside from that, it's probably clearer to use (is (thrown? ..)) or (is (thrown-with-msg? ...)) to check for thrown exceptions.
Example:
(t/is (thrown? java.lang.ClassCastException (s/valid? ::sut/int-value "x"))))
Note that you just write classname as a symbol. Use java.lang.Exception if you don't care about the exact Exception.
What is the proper way to do the following in clojure?
(ns todo.test.models.task
(:use [clojure.test]))
(deftest main-test
(is (thrown? Exception (throw Exception "stuff")))
(is (not (thrown? Exception (+ 2 3))))
)
First testcase runs fine but the whole snippet returns "Unable to resolve symbol: thrown?"
is is a macro that looks for the symbol thrown? in its body and build tests.
thrown? is not actually a function you can call. The default behaviour of is fails the test if an exception is thrown that was not beeing looked for, so you can just remove the (not (thrown? from the above example and get the result you are looking for.
thrown? is a special assertion that must show up after is, so you can't nest it in other expressions, so in the context of the is macro, the second assertion will not understand the symbol thrown?.
You could just say:
(deftest main-test
(is (thrown? Exception (throw (Exception. "stuff"))))
(is (= 5 (+ 2 3))))
If an exception is thrown in (+ 2 3), clojure.test will report 1 :error and 0 :fail and dump the stack trace.
Also note that your (throw Exception "stuff") is incorrect - you need to construct the Exception correctly inside the throw.
Use doseq if you want to do it for many statements:
(testing "bla"
(doseq [x [1 2 3 4]]
(my-dangerous-func! x)))
I know this is an old question but..
In addition to the above answers, if you really want a not-thrown? assertion, you can extend the is macro by adding your own e.g.
(defmethod assert-expr 'not-thrown? [msg form]
;; (is (not-thrown? c expr))
;; Asserts that evaluating expr does not throws an exception of class c.
;; Returns the exception thrown.
(let [klass (second form)
body (nthnext form 2)]
`(try ~#body
(do-report {:type :pass, :message ~msg,
:expected '~form, :actual nil})
(catch ~klass e#
(do-report {:type :fail, :message ~msg,
:expected '~form, :actual e#})
e#))))
This should then work as your original expectations
((deftest main-test
(is (thrown? Exception (throw (Exception. "stuff"))))
(is (not-thrown? Exception (+ 2 3)))))
However, please note that clojure.test will always report an error if an exception occurs in your function but if you have a special use-case for this, there you go.
In the following code, Clojure (1.2) is printing the wrong message:
(try
(let [value "1,a"]
(map #(Integer/parseInt %) (.split value ",")))
(catch NumberFormatException _ (println "illegal argument")))
This should print "illegal argument", but instead it prints a (1#<NumberFormatException java.lang.NumberFormatException: For input string: "a">.
What am I doing wrong?
Is this because of the lazy sequence returned by map? How should it be written?
The try special form only catches exceptions that are raised during during the dynamic extent of the body code. Here map is returning a lazy sequence, which then is passed out of the try special form and returned. The printer then evaluates the sequence, and at that point the exception is thrown.
Wrapping the map in doall should fix your problem.