Try-Catch-Finally Blocks in Java

Master exception handling using try-catch-finally blocks, understand exception types, checked vs unchecked exceptions, and the exception hierarchy for the OCP 21 exam.

Table of Contents

1. Exception Basics

An exception is an event that occurs during program execution that disrupts the normal flow of instructions. Java provides a robust exception handling mechanism.

1.1 What are Exceptions?

Exceptions represent error conditions or unexpected situations that occur during program execution. Examples include:

  • File not found
  • Division by zero
  • Array index out of bounds
  • Null pointer access
  • Network connection failure

1.2 Exception Handling Benefits

  • Separates error handling code from normal code
  • Provides a way to propagate errors up the call stack
  • Allows graceful error recovery
  • Makes code more robust and maintainable

2. Exception Hierarchy

All exceptions in Java inherit from the Throwable class.

2.1 Exception Hierarchy Structure

Hierarchy:
Throwable ├── Error (unchecked) │ ├── OutOfMemoryError │ ├── StackOverflowError │ └── ... └── Exception ├── RuntimeException (unchecked) │ ├── NullPointerException │ ├── IllegalArgumentException │ ├── ArrayIndexOutOfBoundsException │ ├── ClassCastException │ └── ... └── Checked Exceptions ├── IOException ├── FileNotFoundException ├── SQLException └── ...

2.2 Throwable Types

  • Error: Serious problems that applications should not catch (e.g., OutOfMemoryError)
  • Exception: Conditions that applications might want to catch
  • RuntimeException: Unchecked exceptions that occur at runtime
  • Checked Exceptions: Must be declared or handled

3. Checked vs Unchecked Exceptions

3.1 Checked Exceptions

Checked exceptions are exceptions that must be either caught or declared in the method signature using throws .

Example:
import java.io.*;
// Checked exception - must handle or declare public void readFile(String filename) throws IOException {
    FileReader file = new FileReader(filename);
    // Throws FileNotFoundException // ... } // Or catch it public void readFile(String filename) {
    try {
        FileReader file = new FileReader(filename);
    }
catch (IOException e) {
    // Handle exception }
}

3.2 Unchecked Exceptions

Unchecked exceptions (RuntimeException and its subclasses, and Error) do not need to be declared or caught.

Example:
// Unchecked exceptions - no need to declare or catch public void divide(int a, int b) {
    int result = a / b;
    // May throw ArithmeticException (unchecked) }
public void accessArray(int[] arr, int index) {
    int value = arr[index];
    // May throw ArrayIndexOutOfBoundsException (unchecked) }
String str = null;
int len = str.length();
// Throws NullPointerException
(unchecked)

3.3 Comparison

Aspect Checked Unchecked
Compile-time check Yes No
Must handle/declare Yes No
Examples IOException, SQLException NullPointerException, IllegalArgumentException
When to use Recoverable conditions Programming errors

4. Try-Catch Blocks

The try-catch block is used to handle exceptions. Code that might throw an exception is placed in the try block, and exception handling code is placed in the catch block.

4.1 Basic Syntax

Syntax:
try {
    // Code that might throw exception }
catch (ExceptionType e) {
    // Handle exception
}

4.2 Examples

Example:
// Catching specific exception try {
    int result = 10 / 0;
}
catch (ArithmeticException e) {
    System.out.println("Division by zero:" + e.getMessage());
} // Catching multiple exceptions (separate catch blocks) try {
int[] arr = new int[5];
arr[10] = 100;
// ArrayIndexOutOfBoundsException }
catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index out of bounds");
}
catch (NullPointerException e) {
    System.out.println("Null pointer");
} // Catching general exception try {
// Some code }
catch (Exception e) {
    System.out.println("An error occurred:" + e.getMessage());
    e.printStackTrace();
    // Print stack trace } // Accessing exception information try {
    String str = null;
    int len = str.length();
}
catch (NullPointerException e) {
    System.out.println("Exception:" + e.getMessage());
    System.out.println("Class:" + e.getClass().getName());
    e.printStackTrace();
}

4.3 Catch Block Order

Important: When catching multiple exceptions, catch more specific exceptions before more general ones. Otherwise, the general catch block will catch everything and the specific ones will be unreachable.
Example:
// CORRECT: Specific before general try {
    // code }
catch (FileNotFoundException e) {
    // Handle specific exception }
catch (IOException e) {
    // Handle general exception }
catch (Exception e) {
    // Handle any other exception } // WRONG: General before specific (compilation error) try {
    // code }
catch (Exception e) {
    // This catches everything }
catch (IOException e) {
    // Unreachable - compilation error! // Never reached
}

5. Finally Block

The finally block always executes, regardless of whether an exception occurs or not. It's used for cleanup code.

5.1 Finally Block Syntax

Syntax:
try {
    // Code that might throw exception }
catch (ExceptionType e) {
    // Handle exception }
finally {
    // Always executes
}

5.2 Examples

Example:
// Finally executes even if exception occurs try {
    int result = 10 / 0;
}
catch (ArithmeticException e) {
    System.out.println("Exception caught");
}
finally {
    System.out.println("Finally block executed");
    // Always executes } // Finally executes even if no exception try {
    int result = 10 / 2;
    System.out.println("Result:" + result);
}
catch (ArithmeticException e) {
    System.out.println("Exception caught");
}
finally {
    System.out.println("Finally block executed");
    // Always executes } // Finally with return statement public int method() {
    try {
        return 10;
    }
catch (Exception e) {
    return 20;
}
finally {
    System.out.println("Finally");
    // Executes before return // return 30;
    // Would override previous returns }
}

5.3 When Finally Doesn't Execute

Finally block doesn't execute in these cases:

  • JVM exits (System.exit())
  • Infinite loop in try block
  • System crash

6. Exception Handling Flow

6.1 Execution Flow

  1. Code in try block executes
  2. If exception occurs:
    • Matching catch block executes
    • finally block executes
    • Execution continues after try-catch-finally
  3. If no exception:
    • finally block executes
    • Execution continues after try-catch-finally
Example:
public void example() {
    try {
        System.out.println("1. Try block");
        int result = 10 / 0;
        // Exception occurs System.out.println("2. After exception");
        // Not executed }
    catch (ArithmeticException e) {
        System.out.println("3. Catch block");
    }
finally {
    System.out.println("4. Finally block");
}
System.out.println("5. After try-catch-finally");
} // Output: // 1. Try block // 3. Catch block // 4. Finally block // 5. After
try-catch-finally

6.2 Exception Propagation

Example:
// Exception propagates up the call stack if not caught public void method1() {
    method2();
    // Exception propagates here }
public void method2() {
    method3();
    // Exception propagates here }
public void method3() {
    int result = 10 / 0;
    // ArithmeticException thrown // If not caught, propagates to method2, then method1, then JVM } // Catching and rethrowing public void method() throws IOException {
    try {
        // Some code that throws IOException }
    catch (IOException e) {
        // Log or handle throw e;
        // Rethrow exception }
}

7. Common Pitfalls

7.1 Swallowing Exceptions

Common Mistake:
// WRONG: Swallowing exception try {
    int result = 10 / 0;
}
catch (ArithmeticException e) {
    // Empty catch block - exception is swallowed! } // CORRECT: Handle or log exception try {
    int result = 10 / 0;
}
catch (ArithmeticException e) {
    System.err.println("Error:" + e.getMessage());
    // Or rethrow, or handle appropriately
}

7.2 Catching Exception Instead of Specific Types

Common Mistake:
// WRONG: Too general try {
    // code }
catch (Exception e) {
    // Catches everything - loses specific exception information } // CORRECT: Catch specific exceptions try {
    // code }
catch (FileNotFoundException e) {
    // Handle file not found }
catch (IOException e) {
    // Handle other IO exceptions }
catch (Exception e) {
    // Handle unexpected exceptions
}

7.3 Return Statement in Finally

Common Mistake:
// WRONG: Return in finally overrides try/catch returns public int method() {
    try {
        return 10;
    }
catch (Exception e) {
    return 20;
}
finally {
    return 30;
    // This value is always returned! }
} // CORRECT: Don't return in finally public int method() {

        int result = 0;
        try {
            result = 10;
        }
        catch (Exception e) {
            result = 20;
        }
        finally {
            // Cleanup code only }

            return result;
        }

8. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • Exception: Event that disrupts normal program flow
  • Throwable: Base class for all exceptions and errors
  • Error: Serious problems (OutOfMemoryError, StackOverflowError)
  • Exception: Conditions applications might catch
  • RuntimeException: Unchecked exceptions (NullPointerException, etc.)
  • Checked Exception: Must be declared or caught (IOException, SQLException)
  • Unchecked Exception: No need to declare or catch (RuntimeException, Error)
  • try Block: Code that might throw exception
  • catch Block: Handles specific exception type
  • finally Block: Always executes (except System.exit())
  • Catch Order: Specific exceptions before general ones
  • Exception Propagation: Uncaught exceptions propagate up call stack
  • getMessage(): Returns exception message string
  • printStackTrace(): Prints stack trace to console
  • Rethrowing: Catch and throw exception again
  • throws Clause: Declares exceptions method may throw
  • Exception Handling Flow: try → catch (if exception) → finally → continue
  • Return in Finally: Overrides return values from try/catch
  • Empty Catch Block: Swallows exception (bad practice)

Post a Comment

0 Comments