【问题标题】:How to break out of a loop if there is an indexOutOfBoundException?如果存在 indexOutOfBoundException,如何跳出循环?
【发布时间】:2014-01-23 08:44:50
【问题描述】:

如果有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] 本身会抛出一个错误,但你能阻止它成为一个错误并简单地跳出给定的循环吗?

【问题讨论】:

  • 什么是Exception?你能用它们做什么?
  • 传说如果不被抓到就会为你爆发
  • 你可以抓住它,但事先检查它会容易得多if(someValue < someArray.length){ // do shizzle }
  • @Sotirios Delimanolis 如果有异常不要继续循环
  • 这些异常是错误编程的结果,应该在开发过程中修复。在 Java 中处理异常的常规方法通常是将抛出异常的代码包装到 try-catch 块中。

标签: java loops indexoutofboundsexception


【解决方案1】:

为什么这应该不难。只需添加 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 的滥用,即使这是一个解决方案,你也不应该以任何方式使用它。

【讨论】:

  • 至少catch 应该只捕获ArrayIndexOutOfBoundsException
  • @HotLicks 你是对的,但是这里可能发生的任何异常(NullPointer 或 ArrayIndexOutOfBounds)对我来说似乎很荒谬。
【解决方案2】:

我认为您要问的是在引发异常之前是否有办法跳出循环。为此,您可以简单地根据数组大小测试数组索引:

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

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 2015-12-28
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2010-09-23
    • 2011-02-14
    • 2013-02-21
    • 1970-01-01
    相关资源
    最近更新 更多