为什么在下面的场景中会抛出不同类型的异常?

时间:2014-04-25 10:20:59

标签: java double java.util.scanner datainputstream

我正在尝试使用ScannerDataInputStream从用户那里获得输入。这是我正在使用的代码:

场景1:

Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double d1 = scanner.nextDouble();

场景2:

DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter a number: ");
double d2 = Double.parseDouble(in.readLine());

abc

等字符提供输入时

在方案1中,我正在 InputMismatchException 。 在方案2中,我收到 NumberFormatException

为什么Scanner抛出不同的异常?有人可以澄清一下。

1 个答案:

答案 0 :(得分:1)

Scanner.nextDouble()的JavaDoc说:

Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

Returns:

The double scanned from the input

Throws:

InputMismatchException - if the next token does not match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed

检查您的Scanner.class来源:

public double nextDouble() {
        // Check cached result
        if ((typeCache != null) && (typeCache instanceof Double)) {
            double val = ((Double)typeCache).doubleValue();
            useTypeCache();
            return val;
        }
        setRadix(10);
        clearCaches();
        // Search for next float
        try {
            return Double.parseDouble(processFloatToken(next(floatPattern())));
        } catch (NumberFormatException nfe) {
            position = matcher.start(); // don't skip bad token
            throw new InputMismatchException(nfe.getMessage());
    }
}

尝试解析时,如果Double.parseDouble()抛出NumberFormatException(根据您的方案2),则Scanner.nextDouble()抛出InputMismatchException(根据您的方案1)。