有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中的try-catch-Python-retry等价物

我对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) 个答案

  1. # 1 楼答案

    当您的问题询问错误处理时,您以IndexError为例,Java中的等价物可以是:

    try {
        //*some code*
    }
    catch(ArrayIndexOutOfBoundsException exception) {
        //handleYourExceptionHere(exception);
    }
    

    关于ArrayIndexOutOfBoundsException,你来看看here, in the documentation。关于例外,一般来说,你可以阅读here

    编辑,根据你的问题编辑,添加更多信息

    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应该离开循环。我还不知道我是否理解你的要求,但我希望这能有所帮助

  2. # 2 楼答案

    你所拥有的几乎和@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;
        }
    }
    
  3. # 3 楼答案

    在@Slaw的帮助下,他决定扫描器将继续输入相同的值,除非我在循环结束时关闭它,这是工作代码

    while (true)
        {
            Scanner reader = new Scanner(System.in);
            try
            {
                System.out.print("Enter an Short: "); //SHORT
                short myShort = reader.nextShort();
                System.out.println(myShort);
                reader.close();
                break;
            }
            catch (InputMismatchException e)
            {
                System.out.println("Error Try again.");
            }
    
        }