JavaError HandlingBeginner

try / catch / finally

The `try-catch-finally` block is used to handle exceptions gracefully, ensuring that critical resources are managed and program flow is controlled even when errors occur.

Review the syntaxStudy the examplesOpen the coding app
try { /* potentially error-prone code */ } catch (ExceptionType e) { /* handle error */ } finally { /* always executed code */ }

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

The `try-catch-finally` block is used to handle exceptions gracefully, ensuring that critical resources are managed and program flow is controlled even when errors occur.

The `try-catch-finally` construct is Java's primary mechanism for structured exception handling. The `try` block encloses code that might throw an exception. If an exception occurs within the `try` block, execution immediately jumps to the appropriate `catch` block. A `catch` block specifies the type of exception it can handle and contains code to respond to that specific error. Multiple `catch` blocks can be used to handle different exception types. The `finally` block is optional but, if present, its code is guaranteed to execute regardless of whether an exception was thrown or caught. This makes `finally` ideal for cleanup operations, such as closing files, database connections, or releasing locks, ensuring resources are properly managed. Proper exception handling is crucial for creating robust and resilient applications. Best practices include catching specific exceptions rather than broad `Exception`, logging errors for debugging, and using `finally` for resource cleanup to prevent leaks. Avoid catching `Throwable` or `Error` unless absolutely necessary, as these often indicate severe, unrecoverable problems.

Quick reference

Syntax

try { /* potentially error-prone code */ } catch (ExceptionType e) { /* handle error */ } finally { /* always executed code */ }

Inputs

Parameters

ExceptionTypeClass · The type of exception to catch (e.g., `IOException`, `NullPointerException`). Can be a superclass to catch multiple related exceptions.
eVariable · The variable name for the caught exception object, providing details about the error.

See it in practice

Examples

1

Basic try-catch block

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // This will throw an ArithmeticException
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.err.println("Error: Division by zero is not allowed.");
            System.err.println("Exception message: " + e.getMessage());
        }
        System.out.println("Program continues after exception handling.");
    }
}
Output:
Error: Division by zero is not allowed. Exception message: / by zero Program continues after exception handling.

The code attempts division by zero, which throws an `ArithmeticException`. The `catch` block handles it, prints an error message, and the program continues execution.

2

try-catch-finally for resource cleanup

import java.io.FileReader;
import java.io.IOException;

public class FileReadExample {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            reader = new FileReader("nonexistent.txt"); // Might throw FileNotFoundException
            int charCode = reader.read(); // Might throw IOException
            System.out.println("First char: " + (char) charCode);
        } catch (IOException e) {
            System.err.println("An I/O error occurred: " + e.getMessage());
        } finally {
            if (reader != null) {
                try {
                    reader.close(); // Ensure reader is closed
                    System.out.println("FileReader closed.");
                } catch (IOException e) {
                    System.err.println("Error closing reader: " + e.getMessage());
                }
            }
        }
        System.out.println("File operation attempted.");
    }
}
Output:
An I/O error occurred: nonexistent.txt (No such file or directory) FileReader closed. File operation attempted.

The `finally` block ensures that the `FileReader` is closed, even if an `IOException` occurs during file reading or opening. Note the nested `try-catch` for closing.

3

Multiple catch blocks

import java.util.List;
import java.util.ArrayList;

public class MultiCatchExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("item");

        try {
            String s = list.get(1); // IndexOutOfBoundsException
            System.out.println(s.length()); // NullPointerException if s was null
        } catch (IndexOutOfBoundsException e) {
            System.err.println("Index error: " + e.getMessage());
        } catch (NullPointerException e) {
            System.err.println("Null pointer error: " + e.getMessage());
        } catch (Exception e) { // Generic catch for any other unexpected exceptions
            System.err.println("An unexpected error occurred: " + e.getMessage());
        }
        System.out.println("Multi-catch example finished.");
    }
}
Output:
Index error: Index 1 out of bounds for length 1 Multi-catch example finished.

Multiple `catch` blocks handle different specific exceptions. The first matching `catch` block is executed. A general `Exception` catch can be used as a fallback.

4

Multi-catch (Java 7+)

import java.io.IOException;
import java.sql.SQLException;

public class MultiCatchJava7 {
    public static void main(String[] args) {
        try {
            // Simulate a method that might throw multiple exceptions
            if (Math.random() > 0.5) {
                throw new IOException("Simulated IO error");
            } else {
                throw new SQLException("Simulated SQL error");
            }
        } catch (IOException | SQLException e) { // Catch multiple exceptions in one block
            System.err.println("Caught an exception: " + e.getClass().getSimpleName() + " - " + e.getMessage());
        }
    }
}
Output:
Caught an exception: IOException - Simulated IO error OR Caught an exception: SQLException - Simulated SQL error

Java 7 introduced multi-catch, allowing a single `catch` block to handle multiple exception types with a common handler, reducing code duplication.

Debug faster

Common Errors

1

Compile-time Error

Cause: Catching a more general exception type before a more specific one in multiple `catch` blocks.

Fix: Order `catch` blocks from most specific to most general. For example, `catch (FileNotFoundException)` must come before `catch (IOException)`.

try {
    // ...
} catch (Exception e) { // This catches everything
    // Compile-time error: Exception 'java.io.IOException' has already been caught
} catch (IOException e) {
    // This block is unreachable
}
2

Resource Leak

Cause: Failing to close resources (like `FileReader`, `Connection`) in the `finally` block or using `try-with-resources`.

Fix: Always close resources in a `finally` block or, preferably, use the `try-with-resources` statement (Java 7+) for auto-closing `AutoCloseable` resources.

import java.io.FileReader;
import java.io.IOException;
FileReader reader = null;
try {
    reader = new FileReader("file.txt");
    // ...
} catch (IOException e) {
    // ...
}
// Resource 'reader' is not guaranteed to be closed here if an exception occurred

Runtime support

Compatibility

JVMN/AJava 1.0+ (multi-catch Java 7+)

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

The `try-catch-finally` block is used to handle exceptions gracefully, ensuring that critical resources are managed and program flow is controlled even when errors occur.

ExceptionType: The type of exception to catch (e.g., `IOException`, `NullPointerException`). Can be a superclass to catch multiple related exceptions. e: The variable name for the caught exception object, providing details about the error.

Compile-time Error: Order `catch` blocks from most specific to most general. For example, `catch (FileNotFoundException)` must come before `catch (IOException)`. Resource Leak: Always close resources in a `finally` block or, preferably, use the `try-with-resources` statement (Java 7+) for auto-closing `AutoCloseable` resources.