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
- Nested try-catch blocks
- Or chain of fallback calls
- Always have a default
Related Exception Handling exercises
- Practice Age Input Validation with Exceptions in Java
- Practice Aggregate Multiple Exceptions in Java
- Practice Exception Chaining in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler