› Module 9: Exception Handling › 9.1 try, catch, and finally
M O D U L E

Module 9: Exception Handling

Robust error handling with try-catch-finally, checked vs unchecked exceptions, and custom domain exceptions.

9.1 try, catch, and finally

Real-world software encounters runtime anomalies: network dropouts, missing files, arithmetic division by zero, or null pointer dereferences. Java's exception handling mechanism intercepts these failures cleanly, preventing application crashes.

The try-catch-finally Architecture

  • try: Encloses risky code that might throw an exception.
  • catch: Catches and handles specific exception types, restoring orderly flow.
  • finally: Executes unconditionally whether an exception was thrown, caught, or not thrown at all. Standard location for resource cleanup (closing sockets, DB connections, streams).
try {
    int result = 10 / 0; // throws ArithmeticException
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
    System.out.println("Cleanup runs regardless");
}
try { risky code exception catch (Exception e) { handle error no exception finally { always runs }
Figure 9.1 — try → catch on failure → finally always runs.

💡 Placement & Interview Deep-Dive

  • The Finally Return Trap: If a method has a return statement inside the try or catch block, and also has a return inside the finally block, the return in finally overrides everything!
    public static int test() {
        try { return 10; }
        finally { return 20; } // Returns 20!
    }
  • When does a finally block NOT execute? There are only two scenarios:
    1. If System.exit(0) is invoked, which terminates the JVM process immediately.
    2. In catastrophic hardware failures (e.g. power cutoff, OS kill -9, or host machine crash).

9.2 Checked vs Unchecked Exceptions

Every throwable event in Java descends from the root java.lang.Throwable class, which splits into two fundamental branches: Exception and Error.

Checked vs Unchecked Exception Split

  • Checked Exceptions: Exceptions that inherit directly from Exception (excluding RuntimeException). Verified by the compiler at compile-time: the programmer must either catch them or declare them in the method signature using throws (e.g. IOException, SQLException).
  • Unchecked Exceptions (Runtime Exceptions): Exceptions that inherit from RuntimeException. Not checked by the compiler. Represent programming logic flaws (e.g. NullPointerException, ArrayIndexOutOfBoundsException).
  • Errors: Severe system-level failures that applications are not expected to catch or handle (e.g. OutOfMemoryError, StackOverflowError).
Throwable Exception (recoverable) Error (serious, e.g. OOM) Checked (IOException...) Unchecked / RuntimeException (NullPointerException...)
Figure 9.2 — The Throwable hierarchy: Exception vs. Error, and checked vs. unchecked exceptions.

9.3 throw, throws, and Custom Exceptions

Java distinguishes between actively raising an exception and declaring potential exceptions:

  • throw: An executable action statement inside a method body used to instantiate and throw a specific exception:
    if (amount > balance) {
        throw new InsufficientFundsException("Balance too low: " + amount);
    }
  • throws: A clause in a method signature warning callers that the method may propagate checked exceptions:
    public void readFile(String path) throws IOException { ... }
KEY TERM: throw vs. throws

throw actually raises one specific exception, right where you write it. throws is only a signature-level warning label, telling callers 'this method might send a checked exception your way.'

Creating Custom Exceptions

Extend Exception to create a checked exception; extend RuntimeException to create an unchecked exception:

public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}
MODULE COMPREHENSIVE QUIZ

Module 9 Final Quiz

Test your understanding across all 3 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 9 Final Quiz →
Yukti Mascot