LearnFrenzy
Sign in Take a free test

Exception Handling · Exception Handling Programs · Question 5

Sign-up form validation with exceptions in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Write a register(name, email, age) method that throws IllegalArgumentException with a precise message for each invalid field; try several sign-ups and print the results.

Solution
Main.java
public class Main {
    static String register(String name, String email, String ageText) {
        if (name == null || name.isBlank()) throw new IllegalArgumentException("name is required");
        if (!email.matches("[\\w.+-]+@[\\w-]+\\.[a-z]{2,}")) throw new IllegalArgumentException("invalid email '" + email + "'");
        int age;
        try {
            age = Integer.parseInt(ageText);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("age must be a whole number", e);
        }
        if (age < 13) throw new IllegalArgumentException("must be at least 13, got " + age);
        return "welcome " + name.strip() + " (" + age + ")";
    }

    public static void main(String[] args) {
        String[][] forms = {{"Asha", "asha@mail.com", "21"}, {" ", "x@y.in", "30"}, {"Ravi", "ravi@mail", "25"}, {"Meena", "meena@lf.in", "twelve"}, {"Kid", "kid@lf.in", "9"}};
        for (String[] f : forms) {
            try {
                System.out.println(register(f[0], f[1], f[2]));
            } catch (IllegalArgumentException e) {
                System.out.println("rejected: " + e.getMessage());
            }
        }
    }
}

Output Verified by compiling and running

welcome Asha (21)
rejected: name is required
rejected: invalid email 'ravi@mail'
rejected: age must be a whole number
rejected: must be at least 13, got 9

IllegalArgumentException is the standard choice for invalid arguments; the NumberFormatException is kept as the cause.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links