有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何避免布尔方法中未处理的异常?

我试图在这个方法中使用ReflectiveOperationException,但是我得到了UnhandeledException错误,但是当我用

throw new ReflectiveOperationException("izuoizoiuz");

没有错误。如何避免这个UnhandeledException错误

@Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx) {
    try {
        if (Assert.isNull(bean)) {
            logger.info(EXC_MSG_BEAN_NULL, bean.toString());
        }

        String dependentFieldActualValue;
        dependentFieldActualValue = BeanUtils.getProperty(bean, dependentField);
        boolean isActualEqual = stringEquals(dependentFieldValue, dependentFieldActualValue);

        if (isActualEqual == ifInequalThenValidate) {
            return true; // The condition is not met => Do not validate at all.
        }
        return isTargetValid(bean, ctx); // Perform the actual validation on the target field
    } catch (ReflectiveOperationException e) {
        logger.info("Necessary attributes can't be accessed: {}");
        throw new ReflectiveOperationException("izuoizoiuz");
    }
}

共 (2) 个答案

  1. # 1 楼答案

    ReflectiveOperationException是一个“选中”的异常。这意味着您的方法需要声明它可以抛出它:

    public boolean isValid(Object bean, ConstraintValidatorContext ctx) throws ReflectiveOperationException {
    

    另外,请注意,您不必创建新的ReflectiveOperationException。您可以throw e重新播放原始文件,保留其堆栈跟踪等

  2. # 2 楼答案

    这是一个已检查的异常,要么需要用方法签名声明(使用throws),要么需要像现在这样显式抛出

    它由编译器强制执行。 可以使用包装异常将选中的异常转换为未选中的异常

    public Object loadTest (int objId)
    {
    
     try {
    
        Connection c = Database.getConnection();
        PreparedStatement query = conn.prepareStatement(OBJECT_QUERY);
        query.setInt(1, objId);
        ResultSet rs = query.executeQuery();
        ...
     } catch (SQLException ex) {
        throw new RuntimeException("Cannot query object " + objId, ex);
     }
    }