当在Integer类构造函数中传递字符值而不是整数值时,以下代码抛出 NumberFormatException
class Wrap
{
public static void main(String...args)
{
Integer j=new Integer("s");
System.out.println(j);
}
}
当用户输入字符值而不是整数值时,以下代码抛出 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);
}
}
这两个异常似乎都在相同的场景中抛出,那么它们有何区别?
答案 0 :(得分:2)
让我们看一下这两个异常类的规范:
InputMismatchException
特定于Scanner
。它表示无效类型,不一定是无效数字。 NumberFormatException
专门用于尝试将非数字字符串转换为数字。
公共类InputMismatchException 扩展NoSuchElementException
由扫描程序抛出,表示检索到的令牌与预期类型的模式不匹配,或者令牌超出预期类型的范围。
公共类NumberFormatException 扩展IllegalArgumentException
抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式。
答案 1 :(得分:0)
根据Java API,NumberFormatException是“Thrown,表示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式”,并且{ {3}}“由扫描程序抛出,表示检索到的令牌与预期类型的模式不匹配,或者令牌超出预期类型的范围。”
基本上,第一个场景会抛出一个异常,因为该字符串不代表int
。请注意,我们不关心字符串是如何到达那里的。第二种情况给出了一个特定于输入的异常,因为它被Scanner
抛出。