Retry Mechanism in Java: Explanation & Practice

Implement automatic retry on failure

Problem summary

Create a retry mechanism that attempts an operation up to 3 times before giving up.

Starter code

public class Main {
    static int attempts = 0;
    
    static void unreliableOperation() throws Exception {
        attempts++;
        if (attempts < 3) throw new Exception("Failed");
    }
    
    public static void main(String[] args) {
        // Retry up to 3 times
        // Print: Success after <n> attempts OR Failed after 3 attempts
    }
}

Expected output and test cases

  • Success on 3rd try
    Success after 3 attempts
  • Success on 1st try
    Success after 1 attempts
  • All retries fail
    Failed after 3 attempts

Hints

  1. Use loop with try-catch inside
  2. Track attempt count
  3. Break on success

Related Exception Handling exercises

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