Graceful Degradation in Java: Explanation & Practice

Provide fallback when operation fails

Problem summary

Try primary data source, fall back to cache, then default value.

Starter code

public class Main {
    static String fetchFromDB() throws Exception {
        throw new Exception("DB unavailable");
    }
    
    static String fetchFromCache() throws Exception {
        throw new Exception("Cache miss");
    }
    
    public static void main(String[] args) {
        // Try DB -> Cache -> Default
        // Print: Source: <source>, Data: <data>
    }
}

Expected output and test cases

  • All fail, use default
    Source: Default, Data: N/A
  • DB fails, cache works
    Source: Cache, Data: cached_value
  • DB works
    Source: DB, Data: db_value

Hints

  1. Nested try-catch blocks
  2. Or chain of fallback calls
  3. Always have a default

Related Exception Handling exercises

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