How does Validation.Exception in Java work?

Viewed 5036

I am quite new to Java and I am struggeling to understand Exceptions. In an Excercise I was supposed to implement the Interface "exceptions.excercise.Validator" in the class "ValidatorImpl" and the Method "User#validate". I am struggeling to understand what exactly is happening in these lines of codes and I would really appreciate it, if somebody could help me :):

I am not sure if you need the whole java project to understand the code but here's what I don't really understand: *In 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);
    }
}

In ValidatorImpl.java: package exceptions.excercise;

public class ValidatorImpl implements 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");
    }
}

}

I know this is quite a lot. Thank you if you read all of this :)

1 Answers

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) and valid.validateEmailWithRuntimeException(String) both can throw exceptions. If the age is under 0 or over 120 validateAge will throw an ValidationException. The try-catch will catch that and will run the first catch-block, which will output a new UserExeption("age is incorrect"). If the age is valid, validateEmailWithRuntimeException will be called next. This works the same way! If the Email is invalid, a ValidationRuntimeException will be thrown and catched. In this case, the second catch-block will be called and a new UserExeption("mail is incorrect") will be outputted.

Related