Java 如果存在indexOutOfBoundException,如何中断循环?
如果存在Java 如果存在indexOutOfBoundException,如何中断循环?,java,loops,indexoutofboundsexception,Java,Loops,Indexoutofboundsexception,如果存在indexOutOfBoundException,是否可能中断循环?例如: int v = 987; int c = 783; int[] someArray = new int[23]; do{ //do stuff if(someArray[68] == indexOutOfBoundException){ // How can this be done? break; } }while(
indexOutOfBoundException
,是否可能中断循环?例如:
int v = 987;
int c = 783;
int[] someArray = new int[23];
do{
//do stuff
if(someArray[68] == indexOutOfBoundException){ // How can this be done?
break;
}
}while(v > c);
我知道这个
someArray[68]
本身会抛出一个错误,但是你能防止它成为一个错误并简单地跳出一个给定的循环吗?为什么这不难。只需添加try-catch
int v = 987;
int c = 783;
int[] someArray = new int[23];
do{
//do stuff
int val;
try{
val = someArray[68];
}catch(Exception e) {
break;
}
// do some other operation with the val
}while(v > c);
顺便说一句,这只是对try-catch的滥用,即使这是一种解决方案,您也不应该以任何方式使用它。我想您要问的是,是否有办法在引发异常之前打破循环。为此,只需根据数组大小测试数组索引:
int v = 987;
int c = 783;
int[] someArray = new int[23];
do{
// do stuff
int arrayIndex = (some expression);
if (arrayIndex >= someArray.length) break;
int anotherValue = someArray[arrayIndex];
// do something else
}while(v > c);
什么是
异常
?你能用它们做什么?传说如果没有被抓住,它会为你爆发,你可以抓住它,但是如果(someValuetry catch
块中。至少catch
应该只捕获ArrayIndexOutOfBoundsException
@HotLicks您是对的,但是这里可能发生的任何异常(NullPointer或ArrayIndexOutOfBounds)我觉得很可笑。