我对Java还是很陌生,并且正在努力理解Exception。 在一个练习中,我应该在类“ 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.execercise;
公共类ValidatorImpl实现了Validator {
@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");
}
}
}
我知道这很多。 谢谢,如果您阅读所有这些内容:)
First, you have a try-catch block. This will catch exceptions thrown in the try-part and if an exception is found they'll run the catch-block for the type of exception. The methods
valid.validateAge(int)
andvalid.validateEmailWithRuntimeException(String)
both can throw exceptions. If the age is under 0 or over 120validateAge
will throw anValidationException
. The try-catch will catch that and will run the first catch-block, which will output anew UserExeption("age is incorrect")
. If the age is valid,validateEmailWithRuntimeException
will be called next. This works the same way! If the Email is invalid, aValidationRuntimeException
will be thrown and catched. In this case, the second catch-block will be called and anew UserExeption("mail is incorrect")
will be outputted.