5. Control Flow & Exceptions

Control Flow, Exception Architecture & Try-With-Resources

Technical guide to Java switch expressions, Throwable hierarchy, Checked vs Unchecked exceptions, try-with-resources, and AutoCloseable semantics.

โšก Exception Architecture & Throwable Hierarchy

An Exception is an event that disrupts the normal execution flow of a Java application. All exception classes in Java inherit from the java.lang.Throwable superclass:

  • Analogy: An Electrical Circuit Fuse Box & Emergency Responders.
    • java.lang.Error: Structural building damage (e.g., Earthquake or Power Grid Blackout). Application code cannot catch or recover from errors.
    • Checked Exceptions: Mandatory Fire Safety Inspection Permits. The compiler requires you to show proof of a fire extinguisher (try-catch or throws) before you can open for business!
    • Unchecked Runtime Exceptions: Tripping over a loose wire in the office. Bugs caused by improper application code logic (NullPointerException, IndexOutOfBoundsException).
java.lang.Throwable 1. java.lang.Error Fatal JVM Crashing 2. java.lang.Exception Application Recoverable OutOfMemoryError StackOverflowError Checked Exceptions Compile-Time Mandatory Unchecked Runtime Exceptions Logic Bugs IOException SQLException NullPointerException IllegalArgumentException ArrayIndexOutOfBoundsException

๐Ÿ†š Checked Exceptions vs. Unchecked Runtime Exceptions

AttributeChecked Exceptions (Exception)Unchecked Exceptions (RuntimeException)
Compiler EnforcementMandatory. Must catch or declare via throws signatureOptional. Compiler does not enforce handling
Root CauseRecoverable environmental conditions (Missing file, Network drop)Programmatic logic bugs (null dereference, invalid index)
Common ExamplesIOException, SQLException, ClassNotFoundExceptionNullPointerException, IllegalArgumentException, ArithmeticException

๐Ÿ”€ Modern Switch Expressions (Java 14+)

Java 14 introduced clean Switch Expressions featuring arrow syntax (->), yield returns, and exhaustiveness checking:

public class SwitchExpressionDemo {
    public static String getDayType(String day) {
        // Switch as an expression returning a value directly!
        return switch (day.toUpperCase()) {
            case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> "Weekday";
            case "SATURDAY", "SUNDAY" -> "Weekend";
            default -> {
                System.out.println("Validating unexpected input: " + day);
                yield "Unknown Day";
            }
        };
    }

    public static void main(String[] args) {
        System.out.println("Friday is a: " + getDayType("Friday"));
    }
}

๐Ÿงน Automatic Resource Management: try-with-resources

Before Java 7, closing file streams or database connections required verbose finally blocks. Java 7 introduced try-with-resources, which automatically closes any resource implementing the java.lang.AutoCloseable interface:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ResourceCleanupDemo {
    public static void main(String[] args) {
        // AutoCloseable resource instantiated inside try header
        try (BufferedReader reader = new BufferedReader(new FileReader("config.txt"))) {
            String line = reader.readLine();
            System.out.println("Config Read: " + line);
        } catch (IOException e) {
            System.err.println("File I/O Error: " + e.getMessage());
        } 
        // reader.close() is automatically invoked HERE in reverse allocation order!
    }
}

๐Ÿ› ๏ธ Creating Custom Domain Exceptions

// Custom Unchecked Business Exception
public class InsufficientFundsException extends RuntimeException {
    private final double requestedAmount;

    public InsufficientFundsException(String message, double requestedAmount) {
        super(message);
        this.requestedAmount = requestedAmount;
    }

    public double getRequestedAmount() {
        return requestedAmount;
    }
}

โ“ Conceptual Quizzes

Knowledge Check

What is the key difference between Checked and Unchecked Exceptions in Java?

Knowledge Check

Which interface must a resource class implement to be compatible with try-with-resources syntax?


๐Ÿ’ป Practice Problems

Problem: Custom AutoCloseable Database Connection Simulation

Create a class FakeDbConnection that implements AutoCloseable. Instantiate it inside a try-with-resources block in main() to demonstrate automatic resource closure.

On this page