javaexceptiontry-catchinputmismatchexception

java.util.InputMismatchException: For input string: "2147483648"


Below is my code

public class ExceptionHandling {

    public static void main(String[] args) throws InputMismatchException{
        Scanner sc = new Scanner(System.in);
        int a = 0;
        int b = 0;
        try {
            a = sc.nextInt();
            b = sc.nextInt();

            try {
                int c = a / b;
                System.out.println(b);

            } catch (ArithmeticException e) {
                System.out.println(e);
            }
        } catch (InputMismatchException e) {
            System.out.println(e);
        }

    }

}

My main query from the above question is, when I am passing String as input then I am getting java.util.InputMismatchException only. But when I am passing 2147483648 as an input, it gives java.util.InputMismatchException: For input string: "2147483648" as an output.

So can anyone tell me why I am getting For input string: "2147483648" in that case?


Solution

  • My main issue is, while passing "hello" the output is java.util.InputMismatchException. But while passing (2147483648) long in int type the output is= java.util.InputMismatchException: For input string: "2147483648". I want to know why is it printing extra content.

    That is a different question to what you were originally asking, but I will answer anyway.

    The reason you are getting "extra content" as in:

    java.util.InputMismatchException: For input string: "2147483648"
    

    is that you are printing the exception like this:

    System.out.println(e);
    

    This calls toString() on the exception object and prints it. The toString() method for a typical exception is roughly equivalent to this:

    public String toString() {
        return e.getClass().getName() + ": " + e.getMessage();
    }
    

    If you don't want the exception name, just print the exception message:

    System.out.println(e.getMessage());
    

    which would output:

    For input string: "2147483648"
    

    (IMO, that is not the kind of message you should be showing to users. It doesn't explain anything!)


    I want the output to be same for both Hello and 2147483648.

    It will be, I think. For "Hello", the output will be:

    java.util.InputMismatchException: For input string: "Hello"
    

    Finally, if you actually want an intelligible error message, you will need to make more extensive modifications to the code. Unfortunately, neither nextInt() or Integer.parseInt(...) give exception messages that explain why an input string is not an acceptable int value.