Reputation: 63
I'm trying to use a try catch structure to show an error when I try to input a letter into a string. Which exception should I be using for this? the console shows me InputMismatchException but this does not work.
input that works:
beginnen = 1
input that doesn't work:
beginnen = a
it obviously doesn't work cause i'm putting a string into an int, I just want to have a message show up when this occurs
int beginnen;
String error = "Something went wrong";
try {
beginnen = Input.readInt();
}
catch (InputMismatchException IME) {
System.out.println(error);
}
error that shows up:
Exception in thread "main" java.util.InputMismatchException
Upvotes: 0
Views: 3818
Reputation: 21768
If the documentation is foggy, use experiment:
try {
beginnen = Input.readInt();
} catch (Throwable x) {
System.err.println("Catched "+x.getClass().getName());
}
This will print the exact class name for you and you can later change your code to catch the exception of this class. This will also show for you, maybe just nothing is actually thrown.
Upvotes: 2
Reputation: 1157
Your Try/Catch expression looks fine to me, however you've mistakenly referenced error, which is not defined anywhere.
Try changing it to System.out.println(IME.getMessage());
Upvotes: 1