Java 如何避免布尔方法中未处理的异常?
我试图在此方法中使用Java 如何避免布尔方法中未处理的异常?,java,exception,exception-handling,try-catch,Java,Exception,Exception Handling,Try Catch,我试图在此方法中使用ReflectiveOperationException,但我得到UnhandledException错误,但当我使用 throw new ReflectiveOperationException("izuoizoiuz"); 没有错误。如何避免此未处理的异常错误 @Override public boolean isValid(Object bean, ConstraintValidatorContext ctx) { try { if (Asse
ReflectiveOperationException
,但我得到UnhandledException
错误,但当我使用
throw new ReflectiveOperationException("izuoizoiuz");
没有错误。如何避免此未处理的异常
错误
@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");
}
}
ReflectiveOperationException
是一个“选中”的异常。这意味着您的方法需要声明它可以抛出它:
public boolean isValid(Object bean, ConstraintValidatorContext ctx) throws ReflectiveOperationException {
另外,请注意,您不必创建新的ReflectiveOperationException。您可以
抛出e
以重新抛出原始文件,保留其堆栈跟踪,等等。这是一个已检查的异常,需要使用方法签名声明(使用抛出),或者需要像现在这样显式抛出
它由编译器强制执行。
您可以使用包装异常将选中的异常转换为未选中的异常
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);
}
}
这只有在超类声明它也抛出
ReflectiveOperationException
(或超类)时才可能发生。否则,您必须重新显示未检查的异常(或以其他方式处理异常)。