Reputation: 1957
Custom RuntimeException class is not instance of Custom Exception class. But RuntimeException is instance of Exception. Why???
I created two exception classes for my project:
public class ABCRuntimeException extends RuntimeException {
//Functions...
}
public class ABCException extends Exception {
//Functions...
}
Now I am trying to handle those exception like this:
try{
//Code which throw ABCRuntimeException
} catch(Exception e) {
if(e instanceof ABCException) {
System.out.println("Is instance of ABCException");
} else if(e instanceof Exception) {
System.out.println("Is instance of Exception");
}
}
The output is Is instance of Exception
. Why ABCRuntimeException is not instance of ABCException.
And how to handle such exception scenario so that i can apply common logic for both ABCRuntimeException and ABCException without putting OR operator in if condition?
Upvotes: 0
Views: 897
Reputation: 1482
Extending exceptions of multiple classes is possible in java. If you extend it from ABCException and other parent exceptions this should work.
Upvotes: 0
Reputation: 279880
Why
ABCRuntimeException
is not instance ofABCException
.
Because you didn't define it that way
public class ABCRuntimeException extends RuntimeException
public class ABCException extends Exception
And how to handle such exception scenario so that i can apply common logic for both ABCRuntimeException and ABCException without putting OR operator in if condition?
In this case, where your exceptions only share Exception
as a supertype, ||
is appropriate. (You could also catch Exception
if you didn't care about other types of exceptions thrown.)
Upvotes: 2