Modern Java APIs · 8 min read · Beginner
Exceptions & Try-With-Resources
Distinguish checked vs. unchecked exceptions and auto-close resources cleanly with try-with-resources.
What you'll learn
- Understand checked exceptions (IOException) vs. unchecked RuntimeExceptions
- Use try-with-resources to guarantee AutoCloseable cleanup
- Throw meaningful custom domain exceptions
In Java, any resource implementing AutoCloseable (files, database connections, HTTP streams) should be opened inside try (var res = ...). Java automatically invokes res.close() when the block finishes, even if an exception is thrown.
Fill-in-the-Blank Exercise
Catch & Handle Exception
Catch IllegalArgumentException and print its message.
{
validate(-5);
} (IllegalArgumentException e) {
System.out.println(e.getMessage());
}Live Code Lab
JavaExceptionsDemo.java
Expected OutputClick “Run Live” to compile with OpenJDK 21
Parsed: 42 Handled: Must be > 0
Check Your Understanding
Score: 0 / 1
1. What does Java's try-with-resources statement guarantee?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.