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?
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());
If you what the exception name without the message:
System.out.println(e.getClass().getName());
And so on.
(IMO, none of these are the kind of message you should be showing to users. They don't explain the problem in terms that a user would understand!)
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 explains:
int
is expected, andint
value.Addressing this in a general way is difficult. The Scanner.nextInt
method doesn't "understand" what the number means in the context of the call. In the particular case, you could call sc.next()
to get the string, and manually test if it is an out-of-range integer or something else. But be aware that the Scanner.nextInt
uses locale-sensitive parsing.