Custom Exception: Age Validation

easy Exception Handling

Problem

Each input line has one integer: an age. A valid age is from 0 to 150. For a valid age print ok followed by the age. For an invalid age print invalid age followed by the age. Create your own exception class for the invalid age and catch it.

Constraints

  • 1 <= lines <= 10^4

Examples

Input

25
-1

Output

ok 25
invalid age -1

Solutions

Best approachTime O(n)Space O(n)

A custom exception makes the error meaningful: catch (InvalidAgeException) says exactly what we handle. In Java, a checked exception must be declared with throws or caught.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process lines.
 * Input   : Several lines.
 * Output  : One line per age.
 * Approach: Custom exception class.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // Step 1: A custom exception is a new class that extends Exception. The name tells what went wrong.
        static class InvalidAgeException extends Exception {
            InvalidAgeException(String message) {
                super(message);
            }
        }

        // Step 2: The method declares with "throws" that it can fail. It throws our exception for a bad age.
        static void checkAge(long age) throws InvalidAgeException {
            if (age < 0 || age > 150) {
                throw new InvalidAgeException("invalid age " + age);
            }
        }

    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(String[] lines) {
        String[] output = new String[lines.length];
        for (int i = 0; i < lines.length; i++) {
            long age = Long.parseLong(lines[i]);

            // Step 3: Try the check. If it throws our exception, catch it and print its message.
            try {
                checkAge(age);
                output[i] = "ok " + age;
            } catch (InvalidAgeException error) {
                output[i] = error.getMessage();
            }
        }
        return output;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        java.util.List<String> all = new java.util.ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (!line.isEmpty()) {
                all.add(line);
            }
        }
        String[] lines = all.toArray(new String[0]);
        System.out.println(String.join("\n", solve(lines)));
    }
}
Hints (1)
  1. What does 'throws' tell the compiler?