IndexOutOfBoundsException Java后重新启动
我有一个IndexOutOfBoundsException,当这种情况发生时,我想重新启动我的程序或跳回while循环。IndexOutOfBoundsException Java后重新启动,java,loops,while-loop,indexoutofboundsexception,Java,Loops,While Loop,Indexoutofboundsexception,我有一个IndexOutOfBoundsException,当这种情况发生时,我想重新启动我的程序或跳回while循环。 这可能吗?您可以将循环包装在一个循环和一个try/catch块中: boolean done = false; while (!done) { try { doStuff(); done = true; } catch (IndexOutOfBoundsException e) { } } 在此代码中,doStuff(
这可能吗?您可以将循环包装在一个循环和一个try/catch块中:
boolean done = false;
while (!done) {
try {
doStuff();
done = true;
} catch (IndexOutOfBoundsException e) {
}
}
在此代码中,
doStuff()
是您的循环。您可能还想做一些额外的簿记工作,这样您就不会永远重复异常了。您的问题非常笼统,但一般来说,您可以使用catch
语句继续程序流
如果要重新启动程序,请将其执行包装在启动脚本中,如果程序退出时带有
IndexOutOfBoundsException
您可以使用try-and-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
}
}
好吧,很难确切地看到要跳回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
}
}
}
在我看来,你不应该使用catch语句。您正在考虑将indexOutOfBoundsException作为正常程序流程的一部分 在某些情况下可能会发生此错误。例如,它可能是一组未完全填充的字段。我的解决方案是测试导致异常的情况,并采取适当的行动
if (fieldsNotCompleted()){
restart(); // or continue; or ...
} else {
while ( ... ) {
doSomething();
}
}
通过这种方式,您可以使程序更具可读性,更易于修复。你也会根据情况采取行动,而不是因为出现了一些你不确定原因的神奇错误。错误捕获不应该是正常程序流的一部分。这将有效地忽略异常并在while循环中继续。但是,不应该忽略异常,如果可能的话应该修复。@Vulcan-这是一条在没有上下文时适用的一般规则,但是OP可能有理由想再试一次。可能循环(现在是内部循环)正在与另一个线程或用户交互。根据程序的逻辑,特定的异常可能需要修复,也可能不需要修复。此问题被否决的原因是因为此问题没有显示研究或任何努力。相关代码也不存在。因为这个问题太笼统,所以它不是一个具体的问题,这正是我们在这里对stackoverflow的期望