Retry operation 3 times

Retry operation 3 times

Hard Java Exceptions 23 views
Explanation Complexity

Problem Statement

Task: call a risky operation and retry up to 3 times on exception. If still fails, throw last exception.

Input Format

A method call that may throw an exception (risky operation).

Output Format

If succeeds within 3 tries → print "Success"
If fails 3 times → throw the last exception

Example

Risky operation fails every time
Exception thrown after 3 attempts

Constraints

• Retry maximum 3 times

• If still failing, rethrow the last exception

Concept Explanation

We attempt the risky operation up to 3 times.
If it succeeds, stop retrying.
If it fails all 3 times, throw the last exception.

Step-by-Step Explanation

1.Initialize attempt = 0.

2.Initialize Exception lastException = null.

3.While attempt < 3:

• Try to perform risky operation.

• If success → return.

• If exception occurs:

• Store exception in lastException.

• Increment attempt.

4.After loop ends:

• Throw lastException.

Concept Explanation

We attempt the risky operation up to 3 times.
If it succeeds, stop retrying.
If it fails all 3 times, throw the last exception.

Step-by-Step Explanation

1.Initialize attempt = 0.

2.Initialize Exception lastException = null.

3.While attempt < 3:

• Try to perform risky operation.

• If success → return.

• If exception occurs:

• Store exception in lastException.

• Increment attempt.

4.After loop ends:

• Throw lastException.

Input / Output Format

Input Format
A method call that may throw an exception (risky operation).
Output Format
If succeeds within 3 tries → print "Success"
If fails 3 times → throw the last exception
Constraints
• Retry maximum 3 times

• If still failing, rethrow the last exception

Examples

Input:
Risky operation fails every time
Output:
Exception thrown after 3 attempts

Example Solution (Public)

Java
static int retry3(java.util.concurrent.Callable<Integer> op) throws Exception{Exception last=null;for(int i=0;i<3;i++){try{return op.call();}catch(Exception e){last=e;}}throw last;}

Official Solution Code

static int retry3(java.util.concurrent.Callable<Integer> op) throws Exception{Exception last=null;for(int i=0;i<3;i++){try{return op.call();}catch(Exception e){last=e;}}throw last;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.