Reputation: 309
I'm a beginner with Java and was attempting to catch the exception 'InputMismatchException'. Below is my code, I hope it is easy to read, apologies in advance if it's not formatted well. It builds fine and executes, but if I input a character for example the 'catch' doesn't function and the error comes up;
"Exception in thread "main" java.util.InputMismatchException"
I believe everything else in the code works fine including the 'try', and I don't have anything going in the catch other than a System.out.print command.
import java.util.*; // imports
public class w4q1
{
public static void main(String[] args)
{
Scanner user_input = new Scanner( System.in ); // declaring Scanner util
System.out.print("Please enter an integer: \n"); // Asks for input
int d = user_input.nextInt();
while (d > 0 || d < 0) // start of while loop, in the event of anything other than zero entered
{
try {
if (d < 0) // if statements
{
System.out.print("The integer " + d + " is negative\n");
break;
}
else if (d > 0)
{
System.out.print("The integer " + d + " is positive\n");
break;
}
else
{
System.out.print("You have not entered an integer\n");
break;
}
}
catch (InputMismatchException e) // Error message for letters/characters and decimals
{
System.out.print("You have entered an incorrect value, please restart the program\n");
}
}
if (d == 0)
{
System.out.print("A zero has been entered\n");
}
}
}
Upvotes: 0
Views: 1991
Reputation: 26
Put a try-catch block around this code
int d = user_input.nextInt();
and by so doing ,you also need to change the current code a little bit to make it OK. Good Luck !
Upvotes: 0
Reputation: 151
If indeed the exception is not getting caught, then the resulting stack trace should show you the actual line of code which threw the exception. Looking at the code, I'm going to guess that this is where the exception occurs:
user_input.nextInt();
I would recommend you look at the stack trace and see if you can confirm this.
Upvotes: 0
Reputation: 178243
If you are still receiving an InputMismatchException
even though you have a try-catch block, then the exception must be coming from somewhere outside of your try-catch block.
Look at what else outside the try-catch block can throw an InputMismatchException
and put a try-catch block around that statement, or expand your existing try-catch block to include that statement.
Upvotes: 1