0

I am new to java and was trying to implement the isInstance() in a particular exception handling scenario.

try {

       ....
       ..//some condition
          throws MyException(); //  --> MyException extends RuntimeException

}catch(Exception e){
       if(e.getClass().isInstance(MyException.class))  // --> This returns false
                .. //do something
}

The above isInstance() returns false. When I debug, e.getClass() has a value :

in.soumav.exceptions.MyException (id=133)

and MyException.class has value:

in.soumav.exceptions.MyException (id=133)

Which concept am I missing at?

Soumav
  • 385
  • 1
  • 6
  • 25
  • 1
    Is there a reason why you don't catch the specific Exceptions? Code-reuse? In that case check this: https://stackoverflow.com/questions/11211286/is-it-possible-in-java-to-catch-two-exceptions-in-the-same-catch-block – Jeppe Jan 20 '19 at 11:33
  • 1
    `instanceof` is probably a better choice. – Boris the Spider Jan 20 '19 at 11:33

2 Answers2

2

You got it backwards.

It should be:

if (MyException.class.isInstance(e))

The Javadoc:

boolean java.lang.Class.isInstance(Object obj)

Determines if the specified Object is assignment-compatible with the object represented by this Class.

So, if you want to check if the exception instance reference by e is assignment compatible with the class MyException, you should pass e as an argument to MyException.class.isInstance().

As an alternative, you can use isAssignableFrom:

if (e.getClass().isAssignableFrom(MyException.class))
Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
2

MyException.class is an instance of Class and not of MyException, so

MyException.class.isInstance(e)

should do it, but your purpose should be handled like:

try {

      ....
      ..//some condition
         throws MyException(); //  --> MyException extends RuntimeException

}catch(MyException e){
    ... //do something
}catch(Exception e){
    ...
}
Turo
  • 4,724
  • 2
  • 14
  • 27