KTU OOP Java2024 Scheme • 60M ESE
MODULE 3/Section 3: Exception Handling

try, Multiple catch Clauses, Nested try Statements & finally Execution Flow

HIGH PRIORITY (Prep Guide)Official Syllabus~16 min study
Official KTU 2024 Syllabus Topics Covered Here
try blockcatch clauseMultiple catch clausesNested try statementsfinally blockException handling execution flow

1. Topic Introduction

Once you understand what exceptions are, you need complete mastery over Java's runtime exception control flow: guarding blocks with try, ordering multiple catch clauses safely, unwinding nested try blocks, and guaranteeing cleanup using finally. Tracing try-catch-finally outputs is a staple KTU Part A and Part B question.

2. Start From Zero: Safety Net (try-catch), Specific First-Aid (Multi-Catch) & Closing Lights (finally)

Putting code inside try { ... } is like putting a safety net under tightrope walkers. If a walker slips (ArithmeticException), the rest of the act inside try aborts immediately and drops into the matching **catch net. With Multiple catches**, always place the narrow specialist (ArithmeticException) BEFORE the general doctor (Exception)—otherwise the general doctor grabs every patient first and the specialist sits unreachable! Finally, **finally** is the janitorial rule: whether the walk succeeded, slipped and got caught, or returned early—ALWAYS turn off the stage lights before leaving!

Key Takeaway: In multiple catch, subclasses MUST precede superclasses (or compile error!). finally executes unconditionally (even if an exception isn't caught or a return executes inside try/catch!).

3. Essential Exam Definitions

try and catch Block
try { ... } encloses code that may throw an exception (curly braces mandatory even for 1 statement); catch (ExType e) { ... } defines a handler immediately following try for matching exception objects.
Nested try Statement
A try block placed inside another try block; if an inner try lacks a matching catch, the stack unwinds outward to inspect enclosing try's catch clauses.
finally Block
An optional block after try/catch containing guaranteed cleanup code that executes regardless of whether an exception was thrown, caught, uncaught, or returned early.

4. Detailed Technical Explanation & Syntax

1. Rules for try, catch & Throwable.toString()

The scope of a catch clause is restricted strictly to its immediately preceding try block. Throwable overrides Object.toString() so System.out.println(e) neatly displays the exception class name and message.

Curly braces {} are ALWAYS mandatory on try, catch, and finally—you cannot omit them even for a single statement.

2. Multiple catch Clauses & Unreachable Catch Compile Error

When one try block can raise multiple exception types (e.g., / by zero or invalid array index), attach multiple catch clauses sequentially. The JVM inspects them top-to-bottom, runs the FIRST matching catch, and bypasses all remaining catch clauses.

CRITICAL EXAM RULE: Exception subclasses MUST come BEFORE their superclasses! Putting catch (Exception e) BEFORE catch (ArithmeticException e) triggers a COMPILE ERROR (exception ArithmeticException has already been caught), because Exception catches ArithmeticException too, making the second block unreachable!

3. Nested try Unwinding & finally Execution Guarantees

Nested try blocks push an exception context onto the stack upon entry. If an inner try throws ArrayIndexOutOfBoundsException and only catches ArithmeticException, the inner try pops and the outer try's catch handles it.

finally runs in EVERY scenario (exception thrown & caught, exception NOT thrown, exception uncaught before propagating out, even after return inside try!) — except if the JVM exits via System.exit(0) or crashes catastrophically.

5. Working Principle: Tracing try -> catch -> finally Execution Paths

  1. Path A (No Exception): Entire try executes -> ALL catch blocks skipped -> finally executes -> code after block runs.
  2. Path B (Caught Exception): try stops at throwing line -> matching catch executes -> finally executes -> code after block runs.
  3. Path C (Uncaught Exception): try stops -> no catch matches -> finally STILL executes -> exception unwinds up to caller / default JVM handler (code after block is skipped!).

6. Examination-Ready Diagrams

Diagram 10

Exception Handling Execution Flow

try BlockRisky code executesException?Thrown at runtime?YESNOMatch catch()First matching handler runsSkip catch()Normal path continuesfinally BlockALWAYS executes (cleanup)

Control-flow decision diagram showing how execution branches through try, matching catch handlers, finally cleanup, or default JVM termination.

Key Components
  • try Block: Monitors risky statements; immediately aborts remaining try lines if an exception occurs.
  • Matching catch Clause: Top-to-bottom check for first compatible exception handler (subclass before superclass).
  • finally Block: Always executes (cleanup) whether exception occurred, was caught, or uncaught.
  • Default JVM Handler: Prints stack trace and terminates thread if no matching catch exists anywhere on call stack.
Step-by-Step Flow
  1. Enter try block and execute statements sequentially.
  2. If NO exception occurs: skip all catch blocks -> execute finally -> continue after try-catch.
  3. If exception occurs: create Exception object -> check catch blocks in order -> execute first match -> execute finally -> continue.
  4. If NO catch matches: execute finally -> unwind call stack to caller method (or JVM default handler).
How to Draw in KTU Exam
  • Draw a flowchart: Enter try -> diamond Exception thrown?.
  • No branch -> Skip catch -> Execute finally -> Normal flow continues.
  • Yes branch -> diamond Matching catch in order? -> Yes -> Execute catch -> Execute finally -> Continue; No -> Execute finally -> Propagate to caller / JVM Default Handler.

7. Complete Java Code Examples & Tracing

Multiple `catch`, Nested `try` Unwinding & `finally` TraceTryCatchFinallyTraceDemo.java
Demonstrates subclass-before-superclass ordering, nested try unwinding from inner to outer handler, and unconditional finally execution.
1public class TryCatchFinallyTraceDemo {
2 static void checkNested(int divisor, int index) {
3 try { // Outer try
4 int val = 10 / divisor; // May throw ArithmeticException
5 System.out.println("Division result: " + val);
6
7 try { // Inner try
8 int[] arr = {1, 2};
9 System.out.println("Array element: " + arr[index]); // May throw ArrayIndexOutOfBounds
10 } catch (ArithmeticException e) {
11 System.out.println("Inner catch handled ArithmeticException");
12 }
13 } catch (ArithmeticException e) {
14 System.out.println("Outer catch handled ArithmeticException: " + e.getMessage());
15 } catch (ArrayIndexOutOfBoundsException e) {
16 System.out.println("Outer catch caught unwound ArrayIndexOutOfBounds!");
17 } catch (Exception e) { // Superclass catch MUST be LAST!
18 System.out.println("Generic catch: " + e);
19 } finally {
20 System.out.println("--> finally ALWAYS executes (divisor=" + divisor + ", index=" + index + ")");
21 }
22 }
23
24 public static void main(String[] args) {
25 checkNested(0, 0); // Outer ArithmeticException
26 checkNested(2, 5); // Inner ArrayIndexOutOfBounds unwinds to Outer catch!
27 checkNested(2, 1); // Clean run
28 }
29}
Expected Output
Outer catch handled ArithmeticException: / by zero
--> finally ALWAYS executes (divisor=0, index=0)
Division result: 5
Outer catch caught unwound ArrayIndexOutOfBounds!
--> finally ALWAYS executes (divisor=2, index=5)
Division result: 5
Array element: 2
--> finally ALWAYS executes (divisor=2, index=1)
Keywords:trycatchfinallyArithmeticExceptionException
Common Exam & Coding Mistakes
  • Placing catch (Exception e) before catch (ArithmeticException e) (unreachable code compile error!).
  • Omitting curly braces on try (try x = 1/0; -> syntax error!).
  • Thinking finally is skipped if try executes a return; statement (actually finally runs RIGHT BEFORE the method returns!).

Real-World Applications

  • finally closes file handles, network sockets, and database connections (conn.close()) even when queries throw exceptions.

Important KTU Exam Points

  • Trace the unreachable catch error clearly (Exception before ArithmeticException).
  • Draw Diagram 10 (Exception Handling Execution Flow) whenever asked for try-catch-finally working.

Memory Techniques & Revision

  • Multi-Catch Ordering: 'Child First, Parent Last!' (Specific -> General).

Common Pitfalls to Avoid

  • Thinking multiple catch clauses execute in sequence for one exception—ONLY the FIRST matching catch executes!

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Multiple catch blocks handle distinct exceptions thrown by a single try, while nested try blocks isolate inner risky operations and unwind unmatched exceptions outward.

  • Multiple Catch Rule: Checked sequentially top-to-bottom; only the first matching handler runs. Exception subclasses MUST precede their superclasses (ArithmeticException before Exception), or compilation fails due to unreachable code.
  • Nested Try Rule: If an inner try does not catch a thrown exception, the stack unwinds and outer try's catch handlers are inspected.
Exam Diagram Note: Include Diagram 10 showing try -> catch -> finally control flow.

Quick Understanding Check

1. What happens if you write catch (Exception e) {} catch (ArithmeticException a) {}?