Search code examples
javadoublejava.util.scannerdatainputstream

Why different type of exceptions thrown in below scenario?


I am trying to get input from user by using Scanner and DataInputStream. Here is my code that I'm using:

Scenario 1:

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

Scenario 2:

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

When providing input as some characters like abc:

In scenario 1, I'm getting InputMismatchException. In scenario 2, I'm getting NumberFormatException.

Why Scanner throws different exception? Can someone please clarify.


Solution

  • The JavaDoc of Scanner.nextDouble() says:

    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
    

    Check your Scanner.class source:

    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());
        }
    }
    

    When trying to parse, if Double.parseDouble() throws NumberFormatException (as per your Scenario 2), then Scanner.nextDouble() throw InputMismatchException (as per your Scenario 1).