Search code examples
javaexceptioninputmismatchexception

Why try/catch InputMisMatchException doesnt work even if I import java.util.InputMisMatchException?


I am trying to write simple calculator and implement some exceptions. I want to catch exception InputMisMatchException if client will try to input letter instead number. I have already import java.util.Input... but this still doesnt work and it end program.

import java.util.InputMismatchException;
import java.util.Scanner;

public class Calculator {
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        boolean menu = true;
        int choice;
        while (menu) {
            menuCalculator();
            System.out.println();
            System.out.println("Select operation: ");
            choice = sc.nextInt();
            sc.nextLine();
            switch (choice) {
                case 1:
                    try{
                    division();
                    } catch (InputMismatchException e){
                        System.err.println("Wrong input. Please enter valid value(s).");
                    }
                    break;
                case 5:
                    System.out.println("Shutting down calculator");
                    menu = false;
                    break;
            }
        }
    }

    public static void menuCalculator() {

        System.out.println("Press to go: \n 1. to divide \n 2. to multiplicate \n 3. to sum \n 4. to substract \n 5. to quit");
    }

    public static void division() {
        double firstNo;
        double secondNo;
        double result;

            System.out.println("Enter first number:");
            firstNo = sc.nextDouble();
            sc.nextLine();
            System.out.println("Enter second number:");
            secondNo = sc.nextDouble();
            sc.nextLine();
            result = firstNo / secondNo;
            if (secondNo == 0) {
                System.out.println("Cannot divide by 0");
            } else {
                System.out.println(firstNo + " / " + secondNo + " = " + result);
            }
    }
}

Solution

  • The exception is thrown by nextInt, but you don't have a try/catch around your call to nextInt, so it doesn't get caught. Move your try/catch block so that the nextInt call is inside it. (You are handling the error from division's nextDouble, just not from nextInt.)

    But: You might consider calling hasNextInt proactively, rather than dealing with the exception reactively. Both approaches have pros and cons.

    Here's how you would use hasNextInt with a loop:

    System.out.println("Select operation (1 - 5): ");
    while (!sc.hasNextInt()) {
        sc.nextLine();
        System.out.println("Please entire a number [1 - 5]:");
    }
    choice = sc.nextInt();
    sc.nextLine();
    switch (choice) {
    // ...
    

    or to handle range checking as well, something like:

    do {
        System.out.println("Select operation (1-5): ");
        choice = -1;
        if (!sc.hasNextInt()) {
            System.out.println("Please enter a number (1-5, inclusive)");
        } else {
            choice = sc.nextInt();
            if (choice < 1 || choice > 5) {
                System.out.println(choice + " isn't an option, please enter a number (1-5, inclusive");
            }
        }
        sc.nextLine();
    } while (choice < 1 || choice > 5);
    switch (choice) {
    // ...