Java中的Python重试等效

我对 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”时,循环重新运行并再次提示用户,直到用户提供正确的输入为止。我希望这能说明我希望它做什么。


冉冉说
浏览 136回答 3
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;    }}

胡说叔叔

当您的问题询问错误处理并且您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应该离开循环。我不知道我是否理解你在问什么,但我希望这会有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java