如何在不跳出 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

更新時間:2019-9-12

9K+ 瀏覽數

開啟你的 職業

獲得認證,完成課程

立即開始
廣告