5 · Intermediate · lesson 25 of 41

Exceptions & try-with-resources

Handling failure without cluttering happy paths.

Java
try (var reader = Files.newBufferedReader(path)) {
    return reader.readLine();
} catch (NoSuchFileException e) {
    return "";
} catch (IOException e) {
    throw new RuntimeException("read failed", e);
}

// Custom exception
class NotFoundException extends RuntimeException {
    public NotFoundException(String msg) { super(msg); }
}
  • ▸Checked exceptions (extends Exception) must be caught or declared.
  • ▸Unchecked (extends RuntimeException) don't require a throws clause.
  • ▸try-with-resources closes AutoCloseable resources in reverse order.
Key takeaways
  • ✓Catch narrow types first, wide types last.
  • ✓Always close I/O — let the compiler do it via try-with-resources.