by @kodeazy
How to re-try/catch a specific java code untill specific condition is reached?
- In this blog we will be discussing on how to
re-try/catch
a specific part of the code until the specific condition is reached. -
lets take two variables as below
int num1=2,num2=0;
- Now if we divide
num1
withnum2
we getjava.lang.ArithmeticException: / by zero
. -
so in the below example we modify the value of
num2
incatch
block andre-try
the condition by adding the whole code insidewhile
loop.import java.util.Random; class RetryCatchExample{ public static void main(String args[]){ int num1=2,num2=0,divisionResult=0; boolean exit=false; while(!exit){ try{ divisionResult=num1/num2; System.out.println("Result after Execution :"+divisionResult); exit=true; } catch(Exception e){ Random rand = new Random(); System.out.println("You Got: "+e+" While Executing"); if(num1<=0){ num1=rand.nextInt(10); } else if(num2<=0){ num2=rand.nextInt(10); } System.out.println("Re-trying to execute the Program after resolving the exception"); } } } }
Output:
D:\java>javac RetryCatchExample.java D:\java>java RetryCatchExample You Got: java.lang.ArithmeticException: / by zero While Executing Re-trying to execute the Program after resolving the exception Result after Execution :0