I wrote this little helper method to search the exception chain for a particular exception (either equals or super c开发者_开发问答lass). However, this seems like a solution to a common problem, so was thinking it must already exist somewhere, possibly in a library I have already imported. So, any ideas on if/where this might exist?
boolean exceptionSearch(Exception base, Class<?> search) {
Throwable e = base;
do {
if (search.isAssignableFrom(e.getClass())) {
return true;
}
} while ((e = e.getCause()) != null);
return false;
}
Take a look into Google Guava project. They have quite a few handy classes including one for exceptions. Eg, functionality you've just requested could be implemented in the next way:
boolean exceptionSearch(Exception base, Class<?> search) {
return Throwables.getCausalChain(base).contains(search);
}
Source code for this class: Throwables
Enjoy!
I don't think there is any utility to help solve this issue. It does make me curious why you would want to do this. There might be a better solution for your root objective.
I found that Apache commons-lang ExceptionUtils.indexOfType does this:
public static int indexOfType(java.lang.Throwable throwable, java.lang.Class type)
精彩评论