JAVA · ОСНОВЫ · LESSON 24

If the input breaks

try and catch · about 17 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Trying a dangerous step.

Sometimes the text cannot be turned into a number. Put it in try so that the program doesn’t end unexpectedly.

try {
    int number = Integer.parseInt("12");
    System.out.println(number);
}

✦ The text of «12» will become the number 12.

STEP 2

Helping you make a mistake

catch catches a mistake if the person has given the wrong text. Instead of a long message, a program can explain the problem simply.

try {
    int number = Integer.parseInt("кот");
    System.out.println(number);
} catch (NumberFormatException error) {
    System.out.println("Нужно число");
}

✦ The word «кот» is «Нужно число».

IN-CLASS PRACTICE

Type the code yourself

Type an example manually. Check the signs and brackets.

public class Main {
    public static void main(String[] args) {
        try {
            int number = Integer.parseInt("кот");
            System.out.println(number);
        } catch (NumberFormatException error) {
            System.out.println("Нужно число");
        }
    }
}
Open the editor for class work
HOMEWORK

Solve it yourself

In try, try turning a string of «abc» into int using Integer.parseInt and output a number. In catch for NumberFormatException, output «Введи число».

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework