What is Exception Handling in Java?: try, catch, throw, finally

Exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can continue instead of crashing abruptly.

Key Keywords

  • try — wraps the code that might throw an exception
  • catch — handles the exception thrown by the try block
  • throw — used to explicitly throw an exception
  • throws — declares that a method might throw an exception
  • finally — a block that always executes, whether an exception occurred or not

Basic Example

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
    System.out.println("This block always runs");
}

Throwing a Custom Exception

class InvalidAgeException extends Exception {
    InvalidAgeException(String message) {
        super(message);
    }
}

void checkAge(int age) throws InvalidAgeException {
    if (age < 18) {
        throw new InvalidAgeException("Age must be 18 or above");
    }
}

Types of Exceptions

  • Checked Exceptions — checked at compile time, such as IOException
  • Unchecked Exceptions — occur at runtime, such as NullPointerException and ArithmeticException
  • Errors — serious problems like OutOfMemoryError that applications usually shouldn't try to catch
You can use multiple catch blocks after a single try to handle different exception types differently, and Java also supports a multi-catch syntax using the pipe (|) operator.

Master Java with Uncodemy

Hands-on training, live projects, and placement support in our Java Programming Course.

Explore the Course

What Happens When an Exception Is Thrown

Understanding the flow of control makes exception handling much less mysterious. When a statement throws an exception, Java follows these steps:

  1. The current statement stops immediately. The remaining lines inside the try block are skipped.
  2. Java checks each catch block in order and runs the first one whose type matches the exception or one of its parent classes.
  3. The finally block runs next, whether a catch matched or not.
  4. If no catch matched, the exception travels up to the method that called this one, and the search repeats there.
  5. If it reaches the top of the call stack without being caught, the thread ends and the JVM prints the stack trace.

Because the first matching catch wins, always put more specific exceptions before general ones. Placing catch (Exception e) above catch (IOException e) is a compile error, since the second block could never run.

try-with-resources and Multi-Catch in Practice

Files, database connections and network sockets must be closed even when something fails. Older code closed them in finally, which was long and easy to get wrong. The try-with-resources statement closes anything that implements AutoCloseable automatically, in reverse order of opening.

import java.io.*;
import java.nio.file.*;

public class ReportReader {
    static int countLines(String path) {
        try (BufferedReader reader = Files.newBufferedReader(Path.of(path))) {
            int lines = 0;
            while (reader.readLine() != null) {
                lines++;
            }
            return lines;
        } catch (NoSuchFileException e) {
            System.out.println("File not found: " + e.getFile());
        } catch (IOException | UncheckedIOException e) {
            System.out.println("Could not read file: " + e.getMessage());
        }
        return -1;
    }
}

The reader is closed whether the method returns normally or an exception is thrown. The pipe in the second catch handles two unrelated exception types with one block of code.

Wrapping an exception without losing the cause

try {
    saveOrder(order);
} catch (SQLException e) {
    throw new OrderSaveException("Could not save order " + order.getId(), e);
}

Passing e as the second argument keeps the original stack trace attached, so the real root cause still appears in the logs.

Best Practices and Common Mistakes

AvoidPrefer
An empty catch block that hides the problemLogging the exception or rethrowing it with context
Catching Exception everywhereCatching the specific types you can actually handle
Printing only e.getMessage()Logging the whole exception so the stack trace is kept
Using exceptions for normal decisionsSimple checks such as if (list.isEmpty())
A return inside finallyKeeping finally for cleanup only

The last row deserves a warning. A return in finally overrides any return from the try block and silently discards an exception that was on its way out. Your program then looks successful when it actually failed.

Choosing checked or unchecked for your own exceptions

  • Extend Exception (checked) when callers can reasonably recover, such as a missing optional file.
  • Extend RuntimeException (unchecked) for programming errors or invalid arguments that callers should fix in code.
  • Give every custom exception a clear message and a constructor that accepts a cause.