Trouble catching IllegalArgumentException thrown from Java method

570 views
Skip to first unread message

Stuart Sierra

unread,
Feb 29, 2008, 5:40:18 PM2/29/08
to Clojure
Hi there,

I want to catch a java.lang.IllegalArgumentException thrown by a
library method.

This works:
user=> (try (throw (new java.lang.IllegalArgumentException))
(catch java.lang.IllegalArgumentException e
"recovered"))
"recovered"

But calling the method doesn't:
user=> (try (. *value-factory* (createURI "this thing"))
(catch java.lang.IllegalArgumentException e
"recovered"))
java.lang.reflect.InvocationTargetException
....
Caused by: java.lang.IllegalArgumentException: Not a valid
(absolute) URI: this thing

Unless I catch the base Exception class:
user=> (try (. *value-factory* (createURI "this thing"))
(catch java.lang.Exception e "recovered"))
"recovered"

Any idea what's going on?
Thanks,
Stuart

Rich Hickey

unread,
Feb 29, 2008, 5:50:48 PM2/29/08
to Clojure
Sure - if you look at the exception that flows through -
java.lang.reflect.InvocationTargetException - that tells you the call
was made via reflection. Any exceptions thrown in reflection calls get
wrapped by the reflection API in InvocationTargetExceptions.

Your options are:

- put a type hint on *value-factory* so the call becomes non-
reflective.

- change your expectations :)

There are lots of situations where exceptions can get wrapped -
reflection, threading APIs, etc. I'm not sure of the viability of
catching exceptions by type, vs catching base exceptions and examining
the cause (using getCause).

Rich

John Cowan

unread,
Feb 29, 2008, 5:51:45 PM2/29/08
to clo...@googlegroups.com
When a method called by reflection throws an exception, Java wraps it
in an InvocationTargetException to deal with the fact that it might be
a checked exception, which can't be thrown by a method that doesn't
declare it. So either you have to catch InvocationTargetException, or
you should lobby to have Clojure modified to unwrap the exception.

--
GMail doesn't have rotating .sigs, but you can see mine at
http://www.ccil.org/~cowan/signatures

Stuart Sierra

unread,
Feb 29, 2008, 11:07:46 PM2/29/08
to Clojure
Ok, now I understand. I didn't realize that reflection would change
the type of the exception. I added a type hint on *value-factory*,
per John Cowan's suggestion, and the catch works. But I'll consider
just catching Exception.

Thanks to you both,
-Stuart
Reply all
Reply to author
Forward
0 new messages