Search code examples
javaexceptionjava.util.scannernumber-formattinginputmismatchexception

how do number format and input mismatch exceptions differ


The following code throws a NumberFormatException when a character value is passed in Integer class constructor instead of an integer value

class Wrap
{
    public static void main(String...args)
    {
        Integer j=new Integer("s");
        System.out.println(j);
    }
}

And the following code throws an InputMismatchException when a character value is input by user instead of an integer value

import java.util.Scanner;

class User
{
    public static void main(String...args)
    {
        Scanner obj=new Scanner(System.in);
        int i=obj.nextInt();
        int j=obj.nextInt();
        System.out.println("sum of numbers input by user");
        System.out.println(i+j);
    }
}

Both the exceptions appear to be thrown in same scenarios, so how do they differ?


Solution

  • Lets look at the specification of these two exception classes :

    InputMismatchException is specific for the Scanner. It indicates invalid type, not necessarily an invalid number. NumberFormatException is specific for trying to convert a non numeric string to a number.

    public class InputMismatchException extends NoSuchElementException

    Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

    public class NumberFormatException extends IllegalArgumentException

    Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.