【问题标题】:Restart after IndexOutOfBoundsException JavaIndexOutOfBoundsException Java 后重启
【发布时间】:2012-08-15 01:25:43
【问题描述】:

我有一个 IndexOutOfBoundsException,当这种情况发生时,我想重新启动我的程序或跳回我的 while 循环。 这可能吗?

【问题讨论】:

  • 这个被否决的原因是因为这个问题没有显示研究或任何努力。相关代码也没有。由于这个问题太笼统,它不是一个具体的问题,这正是我们在 stackoverflow 上所期望的。 ;-)

标签: java loops while-loop indexoutofboundsexception


【解决方案1】:

您可以将循环包装在一个循环和一个 try/catch 块中:

boolean done = false;
while (!done) {
    try {
        doStuff();
        done = true;
    } catch (IndexOutOfBoundsException e) {
    }
}

在此代码中,doStuff() 是您的循环。您可能还需要做一些额外的簿记,这样您就不会永远重复异常。

【讨论】:

  • 这将有效地忽略异常并在while循环中继续。但是,不应忽略异常,如果可能,应予以修复。
  • @Vulcan - 这是在没有上下文时适用的一般规则,但 OP 可能有理由想再试一次。也许循环(现在是内部循环)正在与另一个线程或与用户交互。根据程序的逻辑,特定的异常可能需要也可能不需要修复。
【解决方案2】:

您的问题非常笼统,但通常您使用catch 语句来继续您的程序流程。

如果您想重新启动程序,请将其执行包装在启动脚本中,如果程序以IndexOutOfBoundsException 退出,该脚本会重新启动您的程序。

【讨论】:

    【解决方案3】:

    你可以使用 try 和 catch 块:

    while (condition) {
    try {
    
     // your code that is causing the exception
    
      } catch (IndexOutOfBoundsException e) {
    
        // specify the action that you want to be triggered when the exception happens
       continue; // skipps to the next iteration of your while 
    
     } 
    }  
    

    【讨论】:

      【解决方案4】:

      嗯,很难确切地知道需要做什么才能跳回您的 while 循环。但是:

      当 IndexOutOfBoundsException 发生时,您可以捕获它并执行您需要的操作,例如:

      public static void actualprogram() {
        // whatever here
      }
      
      public static void main(String args[]) {
        boolean incomplete = true;
        while (incomplete) {
          try {
            actualprogram();
            incomplete = false;
          } catch (IndexOutOfBoundsException e) {
            // this will cause the while loop to run again, ie. restart the program
          }
        }
      }
      

      【讨论】:

        【解决方案5】:

        在我看来,你不应该使用 catch 语句。您正在考虑将 indexOutOfBoundsException 作为正常程序流程的一部分。

        在某些情况下可能会发生此错误。例如,它可能是一组未完全填写的字段。我的解决方案是测试导致您的异常的情况并采取适当的行动。

        if (fieldsNotCompleted()){
            restart(); // or continue; or ...
        } else {
            while ( ... ) {
                doSomething();
            }
        }    
        

        通过这种方式,您可以使您的程序更具可读性并且更易于修复。您也根据情况采取行动,而不是针对出现的一些您不确定原因的神奇错误。错误捕获不应成为正常程序流程的一部分。

        【讨论】:

          猜你喜欢
          • 2013-09-30
          • 1970-01-01
          • 2016-11-15
          • 2016-03-22
          • 2019-08-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-03
          相关资源
          最近更新 更多