3 回答

TA贡献1841条经验 获得超3个赞
你所拥有的几乎就像@Thomas 提到的那样。只需要添加一些括号和分号。它应该看起来像下面的代码。
while(true){
try{
// some code
break; // Prevent infinite loop, success should break from the loop
} catch(Exception e) { // This would catch all exception, you can narrow it down ArrayIndexOutOfBoundsException
continue;
}
}

TA贡献1804条经验 获得超8个赞
当您的问题询问错误处理并且您IndexError作为示例显示时,Java 中的等效项可能是:
try {
//*some code*
}
catch(ArrayIndexOutOfBoundsException exception) {
//handleYourExceptionHere(exception);
}
关于ArrayIndexOutOfBoundsException,你看看这里,在文档中。关于异常,一般来说,你可以在这里阅读。
编辑,根据您的问题版本,添加更多信息...
while(true)
{
try {
System.out.print("Enter a short: ");
short myShort = reader.nextShort();
System.out.println(myShort);
}
catch (InputMismatchException e) {
System.out.println("Error! Try again.");
//Handle the exception here...
break;
}
}
在这种情况下,当InputMismatchException发生时,会显示错误消息并且break应该离开循环。我不知道我是否理解你在问什么,但我希望这会有所帮助。
添加回答
举报