Java Try和Catch inputMismatchException错误

时间:2017-03-12 18:44:29

标签: java inputmismatchexception

我有以下代码

//Ask for weight & pass user input into the object
        System.out.printf("Enter weight: ");
        //Check make sure input is a double 
        weight = input.nextDouble();
        weight =  checkDouble(weight);
        System.out.println(weight);
        System.exit(0); 

方法checkDouble是

Double userInput;
public static Double checkDouble(Double userInput){ 
double weights = userInput;
 try{
    }catch(InputMismatchException e){
        System.out.println("You have entered a non numeric field value");
    }
    finally {
        System.out.println("Finally!!! ;) ");
    }
    return weights;
}

当我输入一个字母而不是一个数字时,我收到以下错误

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at HealthProfileTest.main(HealthProfileTest.java:42)

为什么错误的数据类型输入会遇到catch块中的System.out.println()行?

4 个答案:

答案 0 :(得分:2)

正如您在stacktrace中看到的那样,您的方法不会抛出它,而是通过nextDouble()调用:

at java.util.Scanner.nextDouble(Scanner.java:2456)

你在这里叫它:

weight = input.nextDouble();

所以你应该通过try catch覆盖这部分:

try{

weight = input.nextDouble();
    }catch(InputMismatchException e){
        System.out.println("You have entered a non numeric field value");
    }
    finally {
    System.out.println("Finally!!! ;) ");
}

答案 1 :(得分:1)

InputMismatchException引发了weight = input.nextDouble();,但未在try块中捕获,因此异常会从main方法传播出来并导致程序崩溃

您的checkDouble()方法实际上并未检查任何内容,它只是希望空try块引发InputMismatchException(这是不可能的)。< / p>

您需要在nextDouble()块内调用try才能捕获异常。例如:

try {
  double weight = input.nextDouble();
  System.out.println(weight);
} catch (InputMismatchException e) {
  System.out.println("Invalid number");
}

您可能更喜欢使用Scanner.next()来读取用户的字符串,然后确定它是否是有效的双精度型。这样做的好处是即使用户的原始输入无效也能为您提供原始输入。

String weightText = input.next();
try {
  double weight = Double.valueOf(weightText);
  System.out.println(weight);
} catch (NumberFormatException e) {
  System.out.println(weightText + " is not a valid double.");
}

答案 2 :(得分:0)

首先,你在try块中没有放任何东西。 第二,如果你想放任何引发异常的代码,你想要处理它,你应该把它放在try-catch块中。

Double userInput;
public static Double checkDouble(Double userInput){ 

try{
    double weights = userInput;
}catch(InputMismatchException e){
    System.out.println("You have entered a non numeric field value");
}
finally {
    System.out.println("Finally!!! ;) ");
}
return weights;
}

答案 3 :(得分:0)

Double weight = checkDouble(input);

public static Double checkDouble(Scanner userInput){ 
 Double weights = null;
 try{
      weights = userInput.nextDouble();
    }catch(InputMismatchException e){
        System.out.println("You have entered a non numeric field value");
    }
    finally {
        System.out.println("Finally!!! ;) ");
    }
    return weights;
}