java语言中异常处理的getCause()方法

今天在公司源码里看到这样一段语句
// 调用函数
        Integer rc;
        Object[] args = new Object[] { request, inputNode, outputNode };
       
        try {
            rc = (Integer) method.invoke(this, args);
            log.debug( "调用数据库自定义函数[" + funcName
                     + "]完成,返回:" + String.valueOf(rc)
            );
        }
        catch (IllegalAccessException ex) {
            throw new TxnDataException(ErrorConstant.JAVA_ACCESS_LIMIT,
                    "没有权限访问方法:[" + funcName + "]的缺省构造函数", ex
            );
        }
        catch (InvocationTargetException ex) {
            // 判断是否为应用产生的错误
            if( ex.getCause() != null && ex.getCause() instanceof TxnException ){
                throw (TxnException)ex.getCause();
            }
            else{
                throw new TxnDataException(ErrorConstant.JAVA_INVOCATE_EXCEPTION,
                    "调用方法[" + funcName + "]异常", ex
                );
            }
        }
其中ex.getCause()是第一次见到,因此在baidu上找了找
getCause()返回此异常的原因(尝试加载类时发生错误引发的异常;否则返回 null)

getCause 
public Throwable getCause()返回此 throwable 的 cause;如果 cause 不存在或未知,则返回 null。
(该 Cause 是导致抛出此 throwable 的throwable。) 
此实现返回由一个需要 Throwable 的构造方法提供的 cause,或者在创建之后通过 initCause(Throwable) 方法进行设置的 cause。虽然通常不需要重写此方法,但子类可以重写它,以返回一个通过某些其他方式设置的 cause。这适用于在异常链(异常嵌套)机制被加入到 Throwable 之前存在“遗留 Throwable 链机制”的情况。注意,不必 重写任何 PrintStackTrace 方法,所有方法都调用 getCause 方法来确定 throwable 的 cause。 返回: 此 throwable 的 cause,如果 cause 不存在或是未知的,则返回 null。

猜你喜欢

转载自blog.csdn.net/u012501054/article/details/83179685