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應該離開循環。我不知道我是否理解你在問什么,但我希望這會有所幫助。
添加回答
舉報