How do you throw an Exception without breaking a for loop in java?


Whenever an exception occurred in a loop the control gets out of the loop, by handling the exception the statements after the catch block in the method will get executed. But, the loop breaks.

Example

 Live Demo

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

Output

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

One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception.

If you have try catch within the loop it gets executed completely inspite of exceptions.

Example

 Live Demo

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("");
      }
   }
}

Output

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

Updated on: 12-Sep-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements