Abhendra Singh
Abhendra Singh

Reputation: 1957

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?

Upvotes: 0

Views: 897

Answers (2)

Rohith K
Rohith K

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

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

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

Upvotes: 2

Related Questions