3

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?

ryvantage
  • 13,064
  • 15
  • 63
  • 112
  • 1
    Class is a raw type and should be parameterized on your method like (Throwable e, Class> c) – Mark W Jan 09 '14 at 21:27

3 Answers3

7

Try use

Class.isAssignableFrom(Class clazz)

http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class)

Claas Wilke
  • 1,951
  • 1
  • 18
  • 29
4

Look at Class.isAssignableFrom().

user987339
  • 10,519
  • 8
  • 40
  • 45
evanchooly
  • 6,102
  • 1
  • 16
  • 23
1

See the handy method Class.isInstance()

    if( ... c.isInstance(e) ...
ZhongYu
  • 19,446
  • 5
  • 33
  • 61
  • I prefer this solution to `Class.isAssignableFrom()` – Mike B Jan 09 '14 at 22:12
  • @MikeB, is there any particular reason why? Even after reading this question (http://stackoverflow.com/questions/3949260/java-class-isinstance-vs-class-isassignablefrom) I am still having trouble understanding why one is preferable over the other – ryvantage Jan 09 '14 at 22:42
  • @ryvantage, it's mainly a personal preference. The only real advantage that I'm aware of is you don't have to worry about a NullPointerException. – Mike B Jan 10 '14 at 14:40
  • @MikeB, I think then you have the wrong preference. Because with `isAssignableFrom` you have to invoke the `getClass()` method of your parameter, which throws a NPE if it is null. `isInstance` is the method that won't throw a NPE. – ryvantage Jan 10 '14 at 16:42
  • @ryvantage Yes, I said I preferred this solution (the one in the answer this comment is below), which is `c.isInstance(e)` for exactly the reason you point out. – Mike B Jan 10 '14 at 21:56
  • Ahhhhhh haha sorry I didn't see the "to". :) I thought you were saying you prefer `isAssignableFrom()`. Sorry. :) – ryvantage Jan 11 '14 at 02:46