亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java中的Python重試等效

Java中的Python重試等效

冉冉說 2021-07-20 17:01:16
我對 Java 很陌生,我正在嘗試錯誤處理。我非常精通 python,我知道 python 中的錯誤處理會去while True:      try:          *some code*               except IndexError:             continue             break我想知道 java 中異常后重試循環的等價物是什么編輯:這是我到目前為止所擁有的,但是每當拋出異常時,它都會執行一個無限循環,說“輸入一個短路:錯誤再試一次”。while(true)    {        try {            System.out.print("Enter an Short: "); //SHORT            short myShort = reader.nextShort();            System.out.println(myShort);            break;        }        catch (InputMismatchException e) {            System.out.println("Error Try again.");            continue;        }    }澄清我到底想要的是什么。當拋出“InputMismatchException”時,循環重新運行并再次提示用戶,直到用戶提供正確的輸入為止。我希望這能說明我希望它做什么。
查看完整描述

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;

    }

}


查看完整回答
反對 回復 2021-07-23
?
胡說叔叔

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


查看完整回答
反對 回復 2021-07-23
  • 3 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號