Search code examples
javaexceptioncustom-error-handling

RuntimeException Handling By Creating Custom Exception


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?


Solution

  • Why ABCRuntimeException is not instance of ABCException.

    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.)