gpt4 book ai didi

java - 如何在 boolean 方法中抛出三个异常?

转载 作者:行者123 更新时间:2023-11-30 02:13:12 24 4
gpt4 key购买 nike

我是 Java 世界的新手,我试图理解异常,但我没有得到的是; 如何在 boolean 方法中抛出异常? 当我必须在一次捕获中使用三个异常时该怎么办?

@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;
}
return isTargetValid(bean, ctx);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
logger.info("Necessary attributes can't be accessed: {}", e.getMessage());
//I cant throw an exception here...

}
}

或者我可以做到这一点,但它也没有帮助我:我不知道如何在 boolean 方法中使用异常。

@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;
}
return isTargetValid(bean, ctx);
} catch (ReflectiveOperationException e) {
logger.info("Necessary attributes can't be accessed: {}", e.getMessage());
//Here should be my throw new ReflectiveOperationException("ERROR");
}
}

最佳答案

您不能在指定点引发异常,因为方法 isValid 的签名中不包含任何异常。出于教学目的,让我们定义一个自定义异常类型:

static class MyException extends Exception {
public MyException(Exception e) {
super(e);
}
}

然后我们可以将 throws MyException 添加到 isValid 的方法签名中,并实际将其抛出到 multi-catch 中。 。就像,

@Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx) throws MyException {
try {
// ...
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
logger.info("Necessary attributes can't be accessed: {}", e.getMessage());
throw new MyException(e);
}
}

如果您希望这些特定异常返回调用堆栈 - 只需将它们添加到 throws 行并删除 try-catch (或在try-catch(如果您确实出于某种原因想要登录)。

@Override
public boolean isValid(Object bean, ConstraintValidatorContext ctx)
throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// No try-catch. Otherwise the same.
}

关于java - 如何在 boolean 方法中抛出三个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49492409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com