为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 135 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号