当我尝试将字母输入字符串时,我试图使用try catch结构来显示错误。我应该使用哪个异常呢?控制台显示InputMismatchException,但这不起作用。
有效输入:
beginnen = 1
输入无效:
beginnen = a
显然不起作用因为我把一个字符串放进了int型,我只是想在这个发生时显示一条消息
int beginnen;
String error = "Something went wrong";
try {
beginnen = Input.readInt();
}
catch (InputMismatchException IME) {
System.out.println(error);
}
错误显示:
Exception in thread "main" java.util.InputMismatchException
如果文档不清晰,请使用experimental:
try {
beginnen = Input.readInt();
} catch (Throwable x) {
System.err.println("Catched "+x.getClass().getName());
}
这将为您打印确切的类名,您可以稍后更改代码以捕获该类的异常。这也将为您显示,也许实际上什么都没有抛出。
你的Try/Catch表达式对我来说看起来很好,但是你错误地引用了error,这在任何地方都没有定义。
尝试更改为System.out.println(IME.getMessage());