数字格式和输入不匹配异常有何不同

da7*_*da7 2 java exception number-formatting java.util.scanner inputmismatchexception

当在 Integer 类构造函数中传递字符值而不是整数值时,以下代码将引发NumberFormatException

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

当用户输入字符值而不是整数值时,以下代码将引发InputMismatchException

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这两个异常似乎都是在相同的场景中抛出的,那么它们有何不同呢?

Era*_*ran 5

让我们看看这两个异常类的规范:

InputMismatchException是特定于Scanner. 它表示无效类型,不一定是无效数字。NumberFormatException专门用于尝试将非数字字符串转换为数字。

公共类 InputMismatchException 扩展 NoSuchElementException

由扫描程序抛出,指示检索到的令牌与预期类型的​​模式不匹配,或者令牌超出预期类型的​​范围。

公共类 NumberFormatException 扩展 IllegalArgumentException

抛出该异常表示应用程序已尝试将字符串转换为数字类型之一,但该字符串没有适当的格式。