01 / 21

Try / Catch / Finally
Java Exception Handling

Master the art of graceful error handling in Java using structured try/catch/finally blocks to write robust, crash-resistant programs.

Java Exception Handling

What Is an Exception?

An exception is an event that disrupts the normal flow of a program's execution. When something goes wrong at runtime: dividing by zero, accessing a null reference, or reading a missing file: Java creates an exception object and throws it.

ArithmeticException
Division by zero or illegal math operation
NullPointerException
Calling a method on a null reference
IOException
Failed file or network operation

Why Handle Exceptions?

Exception handling lets you anticipate problems and respond gracefully instead of crashing. It separates your normal logic from your error-recovery logic, making code cleaner and more maintainable.

1
Prevent crashes: your program continues running instead of terminating abruptly.
2
User-friendly messages: show a helpful error instead of a cryptic stack trace.
3
Resource safety: close files, database connections, and network sockets even when errors occur.
4
Separation of concerns: keep your main logic clean and handle errors in dedicated blocks.

Java's Exception Hierarchy

Throwable Error Exception StackOverflowError OutOfMemoryError RuntimeException Checked Exceptions NullPointerException ArithmeticException IOException Don't catch these Unchecked (optional) Must handle

The Try/Catch Syntax

Java
try {
    // Code that might throw an exception
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // Handle the exception
    System.out.println("Cannot divide by zero!");
}
try block
Wraps the risky code that might throw an exception. Execution stops at the line that throws.
catch block
Catches a specific exception type and provides recovery logic. Receives the exception object as a parameter.

The Finally Block

Java
Scanner scanner = null;
try {
    scanner = new Scanner(new File("data.txt"));
    String line = scanner.nextLine();
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
} finally {
    // Always runs: exception or not
    if (scanner != null) scanner.close();
}

Execution Flow

Enter try Exception thrown? No try ends normally Yes Matching catch? No Yes catch runs finally runs Continue or Propagate ALWAYS

Checked vs Unchecked Exceptions

Checked Unchecked
When detected Compile time Runtime only
Must handle? Yes: catch or declare No: optional
Extends Exception (directly) RuntimeException
Examples IOException, SQLException NullPointerException, IndexOutOfBoundsException
Typical cause External resources Programming bugs

Multiple Catch Blocks

Java
try {
    int[] arr = {1, 2, 3};
    int val = arr[10];       // throws ArrayIndexOutOfBoundsException
    int x = 10 / 0;          // throws ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index out of bounds!");
} catch (ArithmeticException e) {
    System.out.println("Math error!");
} catch (Exception e) {
    System.out.println("Something else went wrong.");
}

How to Apply Try/Catch/Finally

1
Identify risky code: find operations that could fail: file I/O, parsing, division, array access, network calls.
2
Wrap in try: place only the risky statements inside the try block. Keep it as short as possible.
3
Add specific catch blocks: catch the most specific exception types first. Provide meaningful recovery or error messages.
4
Add finally if needed: use finally to close resources (files, streams, connections) that must be released regardless of outcome.
5
Test both paths: verify your code works when the try succeeds and when each exception is thrown.

Example 1: Safe Division

Java
public static int safeDivide(int a, int b) {
    try {
        return a / b;
    } catch (ArithmeticException e) {
        System.out.println("Error: division by zero");
        return 0;     // fallback value
    }
}
safeDivide(10, 2)
Returns 5. No exception thrown, catch is skipped entirely.
safeDivide(10, 0)
Prints error message, returns 0 as a safe fallback value.

Example 2: File Reading with Finally

Java
BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new FileReader("scores.txt"));
    String line = reader.readLine();
    System.out.println(line);
} catch (FileNotFoundException e) {
    System.out.println("File not found!");
} catch (IOException e) {
    System.out.println("Error reading file.");
} finally {
    try {
        if (reader != null) {
            reader.close(); // This can also throw an exception!
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Example 3: Parsing User Input

Java
public static int parseAge(String input) {
    try {
        int age = Integer.parseInt(input);
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException(
                "Age out of range");
        }
        return age;
    } catch (NumberFormatException e) {
        System.out.println("Not a valid number!");
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
    return -1;  // indicates invalid input
}

Modern Java: Try-With-Resources

Java 7+
// Resources declared in () are auto-closed
try (BufferedReader reader = new BufferedReader(
        new FileReader("data.txt"))) {

    String line = reader.readLine();
    System.out.println(line);

} catch (IOException e) {
    System.out.println("I/O error: " + e.getMessage());
}
// No finally needed: reader is auto-closed!

Common Mistakes

✕ Catching Exception Too Broadly
Using catch(Exception e) as your only catch hides specific errors and makes debugging harder. Catch specific types first.
✕ Empty Catch Blocks
Writing catch(Exception e) {} silently swallows errors. Always log the error or provide a meaningful response.
✕ Wrong Catch Order
Putting a parent class catch before a child class catch causes a compile error. Most specific exception types go first.

Summary Cheat Sheet

Block Purpose Runs When
try Contains risky code Always attempted
catch Handles specific exception Only if matching exception thrown
finally Cleanup / resource release Always (success or failure)
try-with-resources Auto-close resources Replaces manual finally
Required Combos
try-catch, try-finally, or try-catch-finally. A try block alone will not compile.
Golden Rule
Catch the most specific exception type. Only use Exception as a last resort.

Question 1 of 5

What happens if an exception is thrown inside a try block and there is no matching catch block?

Question 2 of 5

What is printed by this code?

Question 3 of 5

Which statement about the finally block is correct?

Question 4 of 5

Why does Java require you to catch IOException but not NullPointerException?

Question 5 of 5

What is the output of this code?