Reputation: 13496
My programs tend to use a lot of wrapped exceptions (SwingWorker
, for instance, wraps all its exceptions in ExecutionException
). So, I am trying to write a method that will allow me to check if an exception or any of its causes is an instanceof
an exception type, but I don't know how (if it is even possible) to pass JUST a class name as an argument to a method.
So far, I have this:
public static boolean errorOrCausesInstanceOfClass(Throwable e, Class c) {
return e != null && (e.getClass().equals(c) || (e.getCause() != null && errorOrCausesInstanceOfClass(e.getCause(), c)));
}
But this will only work if e.getClass()
is exactly equal to c.getClass()
. But I'd like to check using instanceof
to catch subclasses as well.
Is there a way to accomplish this?
Upvotes: 3
Views: 124
Reputation: 19702
See the handy method Class.isInstance()
if( ... c.isInstance(e) ...
Upvotes: 1
Reputation: 1991
Try use
Class.isAssignableFrom(Class clazz)
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class)
Upvotes: 7