如何在不跳出 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,则尽管发生异常,该循环仍将得到完整执行。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

示例

 在线演示

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

更新时间:2019-9-12

9K+ 浏览数

开启你的 职业

获得认证,完成课程

立即开始
广告