如何在不中断Java中的for循环的情况下引发异常?

每当循环中发生异常时,控件就会通过处理异常而退出循环,方法中catch块之后的语句将被执行。但是,循环中断了。

示例

public class ExceptionInLoop{
   public static void sampleMethod(){
      String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
         try {
            for(int i=0; i<=10; i++) {
               System.out.println(str[i]);
               System.out.println(i);
            }
         }catch (ArrayIndexOutOfBoundsException ex){
            System.out.println("Exception occurred");
      }
      System.out.println("hello");
   }
   public static void main(String args[]) {
      sampleMethod();
   }
}

输出结果

Mango
0
Apple
1
Banana
2
Grapes
3
Oranges
4
Exception occurred
Hello

执行循环而不中断的一种方法是将导致异常的代码移到另一个处理该异常的方法。

如果您在循环中有try catch,则无论异常如何,它都会完全执行。

示例

public class ExceptionInLoop{
   public static void print(String str) {
      System.out.println(str);
   }
   public static void sampleMethod()throws ArrayIndexOutOfBoundsException {
      String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
         for(int i=0; i<=10; i++) {
            try {
               print(str[i]);
               System.out.println(i);
            } catch(Exception e){
            System.out.println(i);
         }
      }
   }
   public static void main(String args[]) {
      try{
         sampleMethod();
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("");
      }
   }
}

输出结果

Mango
0
Apple
1
Banana
2
Grapes
3
Oranges
4
5
6
7
8
9
10