0

I want to try and catch in java,
when I wrote the catch part it asked me for a parameter,
the parameter I want to use is ValueError (as meaning in python)

Example:

try {
        System.out.print("Write your weight: ");
        weight = input.nextDouble();
    }
    catch (ValueError){
        System.out.print("You must write your weight in numbers: ");
        weight = input.nextDouble();
    }
moffeltje
  • 4,521
  • 4
  • 33
  • 57
ronald7894
  • 67
  • 1
  • 5
  • Java is not Python, you should `catch (InputMismatchException exceptionName)`. – Maroun Jun 01 '15 at 12:47
  • 1
    What is ValueEroor? Is it your own exception type? Also, don't use exception blocks for normal execution flow. – JamesB Jun 01 '15 at 12:52

2 Answers2

1

When you are working with java if you use some IDEs(like intllij) it will suggest you what exception(s) you should catch and in this situation or when you know what exceptions you should catch(suppose ExceptionType1 and ExceptionType2) your code will be something like :

try {
    //some code with multiple exceptions
} catch (ExceptionType1 ex){
   //some code to handle your exceptions
} catch (ExceptionType2 ex){
   //some code to handle your exceptions
} ....

but in general if you dont know what exception(s) you have, or you dont want to handle all of them, you could catch general Exception something like this:

try {
    //some code with multiple exceptions
} catch (Exception ex){
   //some code to handle your exceptions
} 

and of course you could write your own exceptions

Community
  • 1
  • 1
Lrrr
  • 4,755
  • 5
  • 41
  • 63
1

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.

Always Learning
  • 5,510
  • 2
  • 17
  • 34