我有一个IndexOutOfBoundsException,当发生这种情况时,我想重新启动程序或跳回我的while循环。 这可能吗?
答案 0 :(得分:2)
您可以将循环包装在循环和try / catch块中:
boolean done = false;
while (!done) {
try {
doStuff();
done = true;
} catch (IndexOutOfBoundsException e) {
}
}
在此代码中,doStuff()
是您的循环。你可能还想做一些额外的簿记,这样你就不会永远重复这个例外。
答案 1 :(得分:0)
您的问题很一般,但通常使用catch
语句继续您的程序流程。
如果要重新启动程序,请将其执行包装在启动脚本中,如果程序以IndexOutOfBoundsException
退出,则会重新启动程序。
答案 2 :(得分:0)
你可以使用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
}
}
答案 3 :(得分:0)
嗯,很难确切地知道需要做什么来跳回你的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
}
}
}
答案 4 :(得分:0)
在我看来,你不应该使用catch语句。您正在考虑将indexOutOfBoundsException作为正常程序流程的一部分。
在某些情况下可能会发生此错误。例如,它可能是一组未完全填充的字段。我的解决方案是测试导致您的异常并采取适当行动的情况。
if (fieldsNotCompleted()){
restart(); // or continue; or ...
} else {
while ( ... ) {
doSomething();
}
}
这样,您可以使程序更易读,更容易修复。你也会根据情况采取行动,而不是出现一些你不确定原因的神奇错误。捕获错误不应该是正常程序流程的一部分。