Try this code if you want to check the instance:
class Ideone {
public static boolean isPresent(final Throwable t, final Class<?>[] exceptionArray) {
for (Class<?> exc : exceptionArray) {
if (exc.isAssignableFrom(t.getClass())) {
return true;
}
}
return false;
}
public static void main(String[] args) throws java.lang.Exception {
// your code goes here
Class<?>[] my = { RuntimeException.class };
System.out.println("RuntimeException: " + isPresent(new RuntimeException(), my));
System.out.println("IllegalStateException: " + isPresent(new IllegalStateException(), my));
System.out.println("NoSuchMethodException: " + isPresent(new NoSuchMethodException(), my));
}
}
Results in:
RuntimeException: true
IllegalStateException: true
NoSuchMethodException: false
Or this code if you want to check if the exception class matches:
class Ideone {
public static boolean isPresent(final Throwable t, final Class<?>[] exceptionArray) {
for (Class<?> exc : exceptionArray) {
if (exc.equals(t.getClass())) {
return true;
}
}
return false;
}
public static void main(String[] args) throws java.lang.Exception {
// your code goes here
Class<?>[] my = { RuntimeException.class };
System.out.println("RuntimeException: " + isPresent(new RuntimeException(), my));
System.out.println("IllegalStateException: " + isPresent(new IllegalStateException(), my));
System.out.println("NoSuchMethodException: " + isPresent(new NoSuchMethodException(), my));
}
}
Results in:
RuntimeException: true
IllegalStateException: false
NoSuchMethodException: false
First mistake was passing RuntimeException.class
instead of an instance new RuntimeException()
.
Second, exc
is already a class object you don't need exc.getClass()
.
Third you did't not return false in case it did not find the exception.