0

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?

4

2 に答える 2

2

ABCRuntimeExceptionのインスタンスではないのはなぜですかABCException

あなたがそのように定義していないからです

public class ABCRuntimeException extends RuntimeException 

public class ABCException extends Exception 

また、if 条件に OR 演算子を入れずに ABCRuntimeException と ABCException の両方に共通のロジックを適用できるように、このような例外シナリオを処理する方法は?

この場合、例外Exceptionがスーパータイプとしてのみ共有されるの||が適切です。Exception(スローされる他のタイプの例外を気にしない場合は、キャッチすることもできます。)

于 2014-12-30T20:49:14.447 に答える
0

Java では、複数のクラスの例外を拡張できます。ABCException およびその他の親例外から拡張すると、これは機能するはずです。

于 2014-12-31T07:32:43.427 に答える