zoukankan      html  css  js  c++  java
  • java 检查抛出的异常是否是要捕获的检查性异常或运行时异常或错误

        /**
         * 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 检查抛出的异常是否是要捕获的检查性异常或运行时异常或错误

  • 相关阅读:
    Fruit HDU
    排列组合 HDU
    XOR and Favorite Number CodeForces
    BZOJ-6-2460: [BeiJing2011]元素-线性基
    CDH 安装与部署
    Apache Hadoop集群搭建
    大数据架构与技术选型
    项目落实方案选择思考(KUDU)
    JAVA 高级篇
    大数据就业岗位
  • 原文地址:https://www.cnblogs.com/ghgyj/p/4027898.html
Copyright © 2011-2022 走看看