← KyΕ«kei Master Hub
SCS2108 | Phase Study Card
πŸ‘οΈ -- opens | 0%

Phase 10C: Demystifying Exception Handling & Control Flow

Exception handling is essential for building resilient applications and is heavily tested in exam code traces. Master the Throwable hierarchy, execution order, catch ordering rules, and custom exceptions.

1. The Complete Exception Class Family Tree

In Java, every exception is an object that inherits from java.lang.Throwable. Memorize the exact hierarchy branches:

Throwable (Base Class) / \ Exception Error (Fatal JVM Failures) / \ (OutOfMemoryError, StackOverflowError) Checked Exceptions RuntimeException (Unchecked) (IOException, (NullPointerException, SQLException, ArithmeticException, ClassNotFoundEx) ArrayIndexOutOfBoundsException, IllegalArgumentException)
Category Root Parent Class Compiler Action Real-World Cause
Error java.lang.Error Not checked by compiler. Cannot handle gracefully. JVM hardware or memory failure (e.g. infinite recursion causing StackOverflowError).
Checked Exception Direct child of java.lang.Exception MANDATORY handling! Compiler refuses to build unless caught (`try-catch`) or declared (`throws`). External environment failure (file missing on disk, network packet dropped, database connection severed).
Unchecked Exception Child of java.lang.RuntimeException Optional handling. Compiler ignores it during compilation. Developer logic flaws (calling method on null, dividing by 0, bad index array access).

2. try-catch-finally Control Flow Execution Rules

πŸ›‘ The Circuit Breaker Analogy

Think of try as the electrical circuit running normally. If a surge occurs, the circuit trips immediately (jumps out of try). The catch block is the safety breaker that absorbs the surge. The finally block is the emergency backup generatorβ€”it runs no matter what to keep essential security lights on (closing files/connections).

Execution Paths Demystified:

  1. Path A (No Exception Occurs): try block completes β†’ finally block runs β†’ code continues below.
  2. Path B (Exception Occurs and is Caught): try block aborts at exception line β†’ matching catch block executes β†’ finally block runs β†’ code continues below.
  3. Path C (Exception Occurs but NOT Caught): try block aborts β†’ finally block runs β†’ exception bubbles up call stack to crash thread.
⚠️ Examiner Trap #1: The Catch Block Ordering Rule

Catch blocks MUST be ordered from Most Specific (Subclass) to Most General (Superclass). Putting a general exception catch block first causes a COMPILE ERROR (unreachable code)!

// ❌ COMPILE ERROR! try { FileReader fr = new FileReader("test.txt"); } catch (Exception e) { // πŸ”΄ Catches everything! System.out.println("Exception"); } catch (FileNotFoundException e) { // ❌ Unreachable catch block error! System.out.println("File not found"); }
⚠️ Examiner Trap #2: Return Statements inside finally

If both try (or catch) and finally contain a return statement, the finally return statement OVERWRITES and MASKS the return value or exception from the try block!

public static int testReturn() { try { return 10; } finally { return 20; // ⚠️ Overrides try return! Returns 20! } }

3. throw vs throws & Custom Exception Authoring

Keyword Syntax / Location Purpose Example
throw Inside a method body Explicitly creates and triggers an exception object instance. throw new IllegalArgumentException("Age cannot be negative");
throws In method header declaration Warns callers that this method delegates unchecked/checked exception handling upwards. public void readFile() throws IOException, SQLException

Creating Custom Exceptions (Step-by-Step Code Template):

To create a custom exception class, inherit from Exception (for checked) or RuntimeException (for unchecked):

// 1️⃣ Custom Checked Exception (forces caller try-catch) public class InsufficientFundsException extends Exception { private double shortfall; public InsufficientFundsException(double shortfall) { super("Insufficient funds! You are short by $" + shortfall); this.shortfall = shortfall; } public double getShortfall() { return shortfall; } } // 2️⃣ Usage inside business logic public class BankAccount { private double balance = 100.0; public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount - balance); } balance -= amount; } }

4. Call Stack Unwinding & Multi-Catch Mechanics

When an exception is thrown inside a nested method, Java searches backwards through active stack frames until a matching handler is found:

main() calls methodA() └─> methodA() calls methodB() └─> methodB() throws NullPointerException! └─> No catch in methodB() -> Unwinds to methodA() └─> methodA() has catch (NullPointerException) -> EXCEPTION HANDLED!

Java 7+ Multi-Catch & Try-With-Resources Syntax:

// Multi-Catch Syntax (e variable is implicitly final) try { // Operations throwing multiple exceptions } catch (IOException | SQLException e) { System.out.println("I/O or Database Error: " + e.getMessage()); } // Try-With-Resources (Automatically calls close() on AutoCloseable objects!) try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { System.out.println("Read error: " + e.getMessage()); } // br.close() is automatically executed here!

5. Interactive Self-Test Exam Drills

Q1: Code Output Trace

What is the exact console output of this code snippet?

try { System.out.print("A"); int result = 10 / 0; System.out.print("B"); } catch (ArithmeticException e) { System.out.print("C"); } finally { System.out.print("D"); } System.out.print("E");
OUTPUT: ACDE

Execution Step-by-Step:
1. Prints A inside try.
2. 10 / 0 throws ArithmeticException. Statement B is skipped!
3. Jump to matching catch (ArithmeticException) -> Prints C.
4. finally block executes -> Prints D.
5. Program continues normally below block -> Prints E.

Q2: Checked vs Unchecked Compiler Rule

Method public void process() { throw new IllegalArgumentException(); } has no throws clause and no try-catch. Does it compile?

YES (COMPILES CLEANLY)

Reasoning: IllegalArgumentException extends RuntimeException (it is an Unchecked Exception). Unchecked exceptions do NOT require explicit try-catch blocks or throws declarations in method signatures.

Q3: System.exit() Edge Case

Is there any situation in Java where a finally block will NOT execute?

YES

Scenarios where finally is skipped:
1. Explicit call to System.exit(status) before or inside the try block.
2. Power loss, fatal OS crash, or JVM process killed via `kill -9`.
3. Infinite loop inside try or catch block preventing thread from reaching finally.