java 检查抛出的异常是否是要捕获的检查性异常或运行时异常或错误

时间:2023-11-13 10:53:08
    /**
* Return whether the given throwable is a checked exception:
* that is, neither a RuntimeException nor an Error.
* @param ex the throwable to check
* @return whether the throwable is a checked exception
* @see java.lang.Exception
* @see java.lang.RuntimeException
* @see java.lang.Error
*/
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
} /**
* Check whether the given exception is compatible with the specified
* exception types, as declared in a throws clause.
* @param ex the exception to check
* @param declaredExceptions the exception types declared in the throws clause
* @return whether the given exception is compatible
*/
//如果ex是RuntimeException或者Error,则兼容,如果ex是declaredExceptions种某个类的子类则是
public static boolean isCompatibleWithThrowsClause(Throwable ex, Class<?>... declaredExceptions) {
if (!isCheckedException(ex)) {//如果ex是RuntimeException或者Error,则为true
return true;
}
if (declaredExceptions != null) {
for (Class<?> declaredException : declaredExceptions) {
if (declaredException.isInstance(ex)) {
return true;
}
}
}
return false;
}
isCompatibleWithThrowsClause这个方法用在什么地方?用在抛出指定类型异常的检查中,比如一个方法如果只有抛出某些异常才需要处理的时候可以调用这个方法
    public static void test(){
try {
int a = 1 / 0;
} catch (Exception e) {
if(isCompatibleWithThrowsClause(e, NoSuchFieldException.class)){
//如果是NoSuchFieldException检查性异常才进行处理
//问题是运行时异常和错误也同样要处理
System.out.println("要处理");
}
} }

java 检查抛出的异常是否是要捕获的检查性异常或运行时异常或错误