While - try - catch in Java

advertisements

I need a java program that ask a number between 0 and 2. If the user write 0, the program ends. If the user write 1, it executes one function. If the user write 2, it executes another function. I also want to handle the error "java.lang.NumberFormatException", with a message and in this case, ask again the user for a number, until he writes a number between 0 and 2

I use

public static void main(String[] args) throws IOException {
    int number = 0;
    boolean numberCorrect = false;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while (numberCorrect == false){
            System.out.println("Choose a number between 0 and 2");
            String option = br.readLine();
            number = Integer.parseInt(option);

            try {
                switch(option) {
                case "0":
                    System.out.println("Program ends");
                    numberCorrect = true;
                    break;
                case "1":
                    System.out.println("You choose "+option);
                    functionA();
                    numberCorrect = true;
                    break;
                case "2":
                    System.out.println("You choose  "+option);
                    functionB();
                    numberCorrect = true;
                    break;
                default:
                    System.out.println("Incorrect option");
                    System.out.println("Try with a correct number");
                    numberCorrect = false;
                }
            }catch(NumberFormatException z) {
                System.out.println("Try with a correct number");
                numberCorrect = false;
            }
        }
    }

But with this code the catch(NumberFormatException z) doesn't work and the program don't ask again for a number.


You never actually catch NumberFormatException here. Your code basically does:

while (...) {
    // this can throw NumberFormatException
    Integer.parseInt(...)

    try {
        // the code in here cannot
    } catch (NumberFormatException e) {
        // therefore this is never reached
    }
}

What you want to do here is:

while (!numberCorrect) {
    line = br.readLine();
    try {
        number = Integer.parseInt(line);
    } catch (NumberFormatException ignored) {
        continue;
    }

    // etc
}