Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't printStackTrace work in Clojure?

In both the Joy of Clojure and on Alex Miller's Pure Danger Tech blog-post it is recommended that you can print the last stack using something like the following:

(use 'clojure.stacktrace) 
(java.util.Date. "foo")
(.printStackTrace *e 5)

But I can't get any of their examples to work, and instead just get

java.lang.NullPointerException: null
        Reflector.java:26 clojure.lang.Reflector.invokeInstanceMethod
         (Unknown Source) jtown$eval9755.invoke

What's up with this? .printStackTrace seems to be a Java function from the looks of it, so I am not sure why I am bringing clojure.stacktrace into my namespace, in the first place. I read through the clojure.stacktrace API, though, and see an e function, which seems similar too but is not the *e function, which is in core and is supposed to be binding to the last exception, but isn't. Could somebody straighten me out on the best way to check stack-traces?

like image 445
kurofune Avatar asked Aug 14 '26 22:08

kurofune


1 Answers

There are some special vars available when using the REPL and

*e - holds the result of the last exception.

For instance:

core=> (java.util.Date. "foo")
IllegalArgumentException   java.util.Date.parse (Date.java:615)


core=> (class *e)
java.lang.IllegalArgumentException


core=> (.printStackTrace *e)
java.lang.IllegalArgumentException
    at java.util.Date.parse(Date.java:615)
        <not included.....>

You are right, .printStackTrace is the java method that is invoked on the exception class. This is not very straightforward (since its java interop) so clojure.stacktrace namespace has some utilities about working with stack traces

So after

(use 'clojure.stacktrace)

you can use the stacktrace library instead of java interop:

core=> (print-stack-trace *e)
java.lang.IllegalArgumentException: null
 at java.util.Date.parse (Date.java:615)
 <not included.....>

Obviously in an app, instead of *e, you can do a try - catch and use the related functions as necessary

like image 58
lorthos Avatar answered Aug 16 '26 12:08

lorthos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!