How to continue for loop after exception in java
What you will learn here about exception in java
- How to continue for loop after exception in java
How to continue for loop after exception in java is one of the common interview question which interviewer ask. Here we will see how to continue for loop after exception in java with very simple example
How to continue for loop after exception in java
The answer for How to continue for loop after exception in java is we need to write our logic or code inside try catch block within the for loop.
The sample program is given below where code which causes exception is kept in try block with its corresponding catch block
public class ForExceptionTest { public static void main(String[] args) { for(int i=0;i<5;i++) { try { if(i%2==0) { //This will create exception if number divisible by 0 System.out.println(1/0); } else { System.out.println(i); } } catch(Exception e) { System.out.println("Exception ocuured for index "+i+" and exception is "+e.getMessage()); } } } }
OUTPUT
Exception ocuured for index 0 and exception is / by zero
1
Exception ocuured for index 2 and exception is / by zero
3
Exception ocuured for index 4 and exception is / by zero