Suppressed Exceptions in Java: Explanation & Practice
Handle exceptions during close()
Problem summary
When close() throws an exception, it gets suppressed. Access and print suppressed exceptions.
Starter code
class Resource implements AutoCloseable {
public void use() throws Exception {
throw new Exception("Error during use");
}
@Override
public void close() throws Exception {
throw new Exception("Error during close");
}
}
public class Main {
public static void main(String[] args) {
try (Resource r = new Resource()) {
r.use();
} catch (Exception e) {
System.out.println("Primary: " + e.getMessage());
for (Throwable t : e.getSuppressed()) {
System.out.println("Suppressed: " + t.getMessage());
}
}
}
}Expected output and test cases
- Suppressed exception accessed
Primary: Error during use Suppressed: Error during close
Hints
- Primary exception is from try block
- close() exception is suppressed
- Use getSuppressed() to access them
Related Exception Handling exercises
- Practice Exception Chaining in Java
- Practice Custom AutoCloseable in Java
- Practice Validation with Exceptions in Java
Practice all Exception Handling exercises · Run this idea in the Java compiler