The nextDouble
method of Scanner
(which I assume is the type of input
) can throw a few exceptions. You can only catch a type of exception that is possible to come back. If you are interested specifically if someone typed a bad answer (like 'yes' instead of a number) then you can catch InputMismatchException
. If you're just wanting to capture any error at all you can catch the more generic Exception
. In either case your catch
statement must name the exception type and a variable name like this:
catch (InputMismatchException ex) { ... }
or
catch (Exception ex) { ... }
This way you can do something with the exception by calling methods on the ex
variable.
Also, you show the catch simply trying again. This might work if the user types a bad value once, but not if it happens a second time. A better way to try again would be this:
weight = -1; // so we can tell if a valid weight was given
while (weight < 0) {
try {
System.out.print("Write your weight: ");
weight = input.nextDouble();
}
catch (InputMismatchException ex){
System.out.print("You must write your weight in numbers.");
}
}
This allows the question to be asked until they enter a valid value.