1

I want to check if an instance of a particular exception is present in a generics array. (I expect all elements of the array are to be some exceptions.)

Here's what I have tried:

class Ideone
{
    public static boolean isPresent(final Throwable t, final Class<?>[] exceptionArray){
        for(Class<?> exc : exceptionArray){
            if(t instanceof exc.getClass() ){
                return true;
            }
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        Class<?>[] my = {RuntimeException.class};
        isPresent(RuntimeException.class, my);
    }
}

Here's an IDEOne link if that helps you to simulate. Here, I get the error expected )

On IntelliJ Idea, on hovering, I get the error cannot resolve symbol 'getClass'.

Any Ideas?

Thanks.

Akshay Arora
  • 1,953
  • 1
  • 14
  • 30

2 Answers2

2

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.

flavio.donze
  • 7,432
  • 9
  • 58
  • 91
  • Thanks. This looks good. Please add this link in the answer to help future visitors to this question: http://stackoverflow.com/questions/3949260/java-class-isinstance-vs-class-isassignablefrom – Akshay Arora Apr 11 '16 at 08:02
  • sorry was still working on the answer, now has two options. – flavio.donze Apr 11 '16 at 08:16
  • The new one is better. The downsides of `isAssignableFrom` is that it will match all super classes. – Akshay Arora Apr 11 '16 at 08:17
1

you should change the variable t to represent a Class inheriting from Throwable. Your current implementation requires you to pass an instance of Throwable to the function, which is quite unnecessary if you want to check if a specific Exception is present. By changing it to Class<? extends Throwable> you can simply pass Exception.class and further on you just check if exc is assignable from t

public static boolean isPresent(final Class<? extends Throwable> t, final Class<?>[] exceptionArray){
    for(Class<?> exc : exceptionArray){
        if(exc.isAssignableFrom(t)){
            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(isPresent(RuntimeException.class, my));
    System.out.println(isPresent(IOException.class, my)); 
    System.out.println(isPresent(ArithmeticException.class, my));
}

output:

true
false
true
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33