Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果存在indexOutOfBoundException,如何中断循环?_Java_Loops_Indexoutofboundsexception - Fatal编程技术网

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); 

什么是
异常
?你能用它们做什么?传说如果没有被抓住,它会为你爆发,你可以抓住它,但是如果(someValue@Sotirios Delimanolis如果出现异常,请不要继续循环这些异常是由于编程错误造成的,应在开发过程中修复。Java中处理异常的常规方法通常是将异常抛出代码包装到
try catch
块中。至少
catch
应该只捕获
ArrayIndexOutOfBoundsException
@HotLicks您是对的,但是这里可能发生的任何异常(NullPointer或ArrayIndexOutOfBounds)我觉得很可笑。