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?

1
  • 1
    Class is a raw type and should be parameterized on your method like (Throwable e, Class<?> c) Commented Jan 9, 2014 at 21:27

3 Answers 3

7

Try use

Class.isAssignableFrom(Class clazz) 

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

Sign up to request clarification or add additional context in comments.

Comments

4

Look at Class.isAssignableFrom().

Comments

1

See the handy method Class.isInstance()

 if( ... c.isInstance(e) ... 

6 Comments

I prefer this solution to Class.isAssignableFrom()
@MikeB, is there any particular reason why? Even after reading this question (stackoverflow.com/questions/3949260/…) I am still having trouble understanding why one is preferable over the other
@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.
@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 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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.