Language 3 of 10 · Topic 0.10

Error & Exception Handling: Checked vs Unchecked, try-catch-finally & try-with-resources

1Concept

Java divides exceptions into Checked (compile-time enforced, subclassing Exception like IOException) and Unchecked (runtime errors, subclassing RuntimeException like NullPointerException). try-with-resources automatically closes AutoCloseable resources (database connections, streams) without explicit finally blocks.

2Architecture Diagram

Throwable Hierarchy:
           Throwable
          /         \
     Exception       Error (Fatal JVM OutOfMemoryError)
     /       \
 Checked    RuntimeException (Unchecked: NPE, IndexOutOfBounds)

3Code Example

Stage 0 Language Foundations
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;

public class ExceptionDemo {
    public static void parseData(String input) throws IllegalArgumentException {
        if (input == null || input.isBlank()) {
            throw new IllegalArgumentException("Input payload cannot be null or blank!");
        }
        System.out.println("Parsed payload: " + input);
    }

    public static void main(String[] args) {
        System.out.println("=== Java Exception Handling & Try-With-Resources ===");

        // 1. Try-With-Resources (AutoCloseable)
        String mockFile = "Line 1: Config\nLine 2: Server Settings";
        try (BufferedReader reader = new BufferedReader(new StringReader(mockFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("Read: " + line);
            }
        } catch (IOException e) {
            System.err.println("I/O Error: " + e.getMessage());
        }

        // 2. Handling custom runtime validation
        try {
            parseData("");
        } catch (IllegalArgumentException ex) {
            System.err.println("[Caught RuntimeException] " + ex.getMessage());
        } finally {
            System.out.println("Finally block executed (Guaranteed cleanup).");
        }
    }
}

4Expected Output

=== Java Exception Handling & Try-With-Resources ===
Read: Line 1: Config
Read: Line 2: Server Settings
[Caught RuntimeException] Input payload cannot be null or blank!
Finally block executed (Guaranteed cleanup).

5Key Takeaways

  • Always prefer try-with-resources over manual finally { resource.close(); } blocks.
  • Never catch generic Throwable or suppress exceptions with empty catch blocks.
  • Unchecked exceptions (RuntimeException) should represent programming bugs or invalid arguments.