自定义 RuntimeException 类不是自定义异常类的实例。但 RuntimeException 是 Exception 的实例。为什么???
我为我的项目创建了两个异常类:
public class ABCRuntimeException extends RuntimeException {
//Functions...
}
public class ABCException extends Exception {
//Functions...
}
现在我尝试像这样处理这些异常:
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");
}
}
输出是是异常的实例
。为什么 ABCRuntimeException 不是 ABCException 的实例。
如何处理此类异常情况,以便我可以对 ABCRuntimeException 和 ABCException 应用通用逻辑,而无需在 if 条件中放入 OR 运算符?
最佳答案
Why
ABCRuntimeException
is not instance ofABCException
.
因为你没有这样定义
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?
在这种情况下,您的异常仅共享 Exception
作为父类(super class)型,||
是合适的。 (如果您不关心抛出的其他类型的异常,您也可以捕获Exception
。)
关于java - 通过创建自定义异常来处理运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27712327/