Java 中的 Validation.Exception 如何工作?

How does Validation.Exception in Java work?

我是 Java 的新手,我很难理解异常。 在练习中,我应该在 class "ValidatorImpl" 和方法 "User#validate" 中实现接口 "exceptions.excercise.Validator"。 我正在努力了解这些代码行中究竟发生了什么,如果有人能帮助我,我将不胜感激:):

我不确定您是否需要整个 java 项目来理解代码,但这是我不太理解的地方: *在User.java

public void validate() throws UserException {
    Validator valid = new ValidatorImpl();

    try {
        valid.validateAge(this.getAge());
        valid.validateEmailWithRuntimeException(this.getEmail());
    } catch (ValidationException e) {
        throw new UserException("age is incorrect", e);
    } catch(ValidationRuntimeException e ) {
        throw new UserException("mail is incorrect", e);
    }
}

在ValidatorImpl.java中: 包裹 exceptions.excercise;

public class ValidatorImpl 实现验证器 {

@Override
public void validateAge(int age) throws ValidationException {

    if ((age < 0) || (age > 120)) {
        throw new ValidationException(age + "not betweeon 0 and 120");
    }
}

@Override
public void validateEmailWithRuntimeException(String email) {

    if (email == null) {
        throw new ValidationRuntimeException("email is null");
    }
    if (!email.contains("@")) {
        throw new ValidationRuntimeException("email must contain @sign");
    }
}

}

我知道这很多。 感谢您阅读所有这些:)

首先,您有一个 try-catch 块。这将捕获在 try-part 中抛出的异常,如果发现异常,它们将 运行 异常类型的 catch 块。 valid.validateAge(int)valid.validateEmailWithRuntimeException(String) 方法都可以抛出异常。 如果年龄小于 0 或大于 120 validateAge 将抛出一个 ValidationException。 try-catch 将捕获它并 运行 第一个 catch 块,它将输出 new UserExeption("age is incorrect")。 如果年龄有效,接下来将调用 validateEmailWithRuntimeException。 这也是一样的!如果电子邮件无效,将抛出并捕获 ValidationRuntimeException。在这种情况下,将调用第二个 catch 块并输出 new UserExeption("mail is incorrect")