我正在用 Java 进行一些基本的异常处理。我向用户询问一个数字,当用户提供不同类型的输入时,例如当他/她输入字符串或字符而不是数字时,我会捕获抛出的输入不匹配错误。
我的问题是为什么当我捕获异常或 IOException 时消息返回为“null”。诚然,异常的类型非常具有解释性,但我认为任何异常都会给出更有意义的消息。给出“null”作为消息对于输入不匹配错误来说是常见的还是至少不是唯一的?
这是我的主要方法中的代码
Scanner kb = new Scanner(System.in);
int y;
try
{
System.out.println("Input a number:");
y = kb.nextInt();
}
catch(Exception e) //also tried IOException, but still got "null" as message
{
System.out.println("Error: " + e.getMessage());
System.out.println("Type of exception: " + e.toString());
}
最佳答案
当您需要了解 Java 类的作用时,请始终使用 JavaDoc。
JavaDoc 说 Scanner.nextInt() 可以抛出这些异常:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
如果您查看这三个异常的 JavaDoc,您会发现它们都不是 IOException
的子类。它们最具体的共同祖先是RuntimeException
。
现在看看InputMismatchException
。 JavaDoc 显示它有两个构造函数 - 一个包含消息,另一个不包含任何内容。后一个:
Constructs an InputMismatchException with null as its error message string.
所以你不能保证InputMismatchException.getMessage()不会返回null。在本例中,您已经发现,这就是它的作用。
关于java - 在输入不匹配错误期间从异常获取 "null"作为消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404192/