Question

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?

Was it helpful?

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.

OTHER TIPS

Per the Java API, a NumberFormatException is "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", and an InputMismatchException is "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."

Basically, the first scenario gets an exception thrown because the string doesn't represent an int. Notice that we don't care how the string got there. The second scenario gives an exception specific to input, because it's being thrown by the Scanner.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top