← Java from Scratch Lesson 52 of 88 · 10 XP

Exceptions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An exception is an error object that "flies" up the calls until it's caught. If it isn't caught, the program crashes with a stack trace:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:6)

We catch it with try / catch, and free resources in finally:

try {
    int n = Integer.parseInt(text);
    System.out.println(100 / n);
} catch (NumberFormatException e) {
    System.out.println("not a number: " + e.getMessage());
} finally {
    System.out.println("always runs");
}

To throw your own: throw new IllegalArgumentException("age < 0");

Checked and unchecked. RuntimeException and its descendants (division by zero, null, an index) are unchecked: catching them isn't required. The others (IOException, FileNotFoundException) are checked: the compiler requires either a try/catch or throws IOException in the method's declaration. This is a feature specific to Java.

Task. Finish static int parseAge(String s): if it's not a number, let the NumberFormatException fly; if it's less than 0 or greater than 150, throw an IllegalArgumentException with the text out of range. In main, for each line print the age or error: <message> (for something that isn't a number — error: not a number).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.