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-catchorthrows) 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).
๐ Checked Exceptions vs. Unchecked Runtime Exceptions
| Attribute | Checked Exceptions (Exception) | Unchecked Exceptions (RuntimeException) |
|---|---|---|
| Compiler Enforcement | Mandatory. Must catch or declare via throws signature | Optional. Compiler does not enforce handling |
| Root Cause | Recoverable environmental conditions (Missing file, Network drop) | Programmatic logic bugs (null dereference, invalid index) |
| Common Examples | IOException, SQLException, ClassNotFoundException | NullPointerException, 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
What is the key difference between Checked and Unchecked Exceptions in Java?
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.
String Immutability, String Constant Pool & Mutability
Deep dive into Java String immutability mechanics, String Constant Pool (SCP) memory allocation, intern(), StringBuilder vs StringBuffer performance, and Text Blocks.
Object-Oriented Principles, Interfaces & Polymorphism
Master Java's 4 Pillars of OOP (Encapsulation, Abstraction, Inheritance, Polymorphism), dynamic method dispatch, Abstract classes vs Interfaces, and pattern matching for instanceof.