Retry with Exceptions in Java: Explanation & Practice

Implement retry logic for failures

Problem summary

Implement a retry mechanism that attempts an operation up to 3 times.

Starter code

import java.util.Random;

public class Main {
    static Random random = new Random(42); // Fixed seed for testing
    
    // Simulate operation that fails randomly
    
    public static void main(String[] args) {
        // Retry up to 3 times
        // Print attempt results
    }
}

Expected output and test cases

  • Success on 3rd try
    Attempt 1: Failed
    Attempt 2: Failed
    Attempt 3: Success
  • Immediate success
    Attempt 1: Success
  • All fail
    Attempt 1: Failed
    Attempt 2: Failed
    Attempt 3: Failed
    All attempts failed

Hints

  1. Use for loop for attempts
  2. Break on success
  3. Track attempt count

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler