Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Back to Java
Java Exception Handling Guide

Java Exception Handling Guide

JavaBy Muhammad Fareed
javaexceptionhandling

Short answer: an exception is an object that signals an error during execution. In Java you handle it with try/catch/finally, pass it up with throws, and use try-with-resources to close files and connections safely.

try, catch, finally

try {
    int[] arr = new int[3];
    arr[5] = 10;                       // throws
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index: " + e.getMessage());
} finally {
    System.out.println("Always runs");
}
  • try holds code that might fail.
  • catch handles a specific exception type.
  • finally runs whether or not an exception occurred, which suits cleanup code.
The flow of try, catch and finally in Javatry block: Risky code runs. Exception thrown: An error occurs. catch block: Handles the error. finally block: Always runs: cleanup. Continue: The program goes ontry blockRisky code runsException thrownAn error occurscatch blockHandles the errorfinally blockAlways runs: cleanupContinueThe program goes on
Diagram: The flow of try, catch and finally in Java.

The exception hierarchy

TypeExamplesMust you handle it?
ErrorOutOfMemoryError, StackOverflowErrorNo; the JVM is in serious trouble
Checked (Exception but not RuntimeException)IOException, SQLExceptionYes: catch it or declare it with throws
Unchecked (RuntimeException)NullPointerException, IllegalArgumentExceptionNo; usually a programming bug

All of them extend Throwable. The compiler forces you to deal with checked exceptions because they represent failures outside your program's control, such as a missing file.

throw vs throws

public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

public String read(String path) throws IOException {
    return Files.readString(Path.of(path));
}
  • throw creates and throws an exception at a specific point.
  • throws in a method signature warns callers that the method may throw a checked exception.

Multiple and multi-catch

try {
    process();
} catch (IOException | SQLException e) {
    log.error("Data access failed", e);
} catch (Exception e) {
    log.error("Unexpected error", e);
}

Put more specific exceptions before general ones; otherwise the compiler reports an error.

try-with-resources

Anything that implements AutoCloseable is closed automatically, even when an exception occurs:

try (BufferedReader reader = Files.newBufferedReader(Path.of("data.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    System.err.println("Read failed: " + e.getMessage());
}

This replaces long finally blocks that closed resources manually.

Custom exceptions

public class InsufficientFundsException extends Exception {
    private final double shortfall;

    public InsufficientFundsException(String message, double shortfall) {
        super(message);
        this.shortfall = shortfall;
    }

    public double getShortfall() { return shortfall; }
}

Extend Exception for recoverable, checked conditions and RuntimeException for programming errors or when you do not want to force callers to catch it.

Wrap and rethrow with the cause

try {
    repository.save(user);
} catch (SQLException e) {
    throw new UserServiceException("Could not save user", e);
}

Passing the original exception as the cause keeps the full stack trace for debugging.

Best practices

  • Never swallow exceptions with an empty catch block. At least log them.
  • Catch the most specific type you can handle; avoid catching Throwable.
  • Do not use exceptions for normal control flow. They are slow compared with a simple check.
  • Add useful messages with the values involved, but never include passwords or personal data.
  • Fail early: validate arguments at the start of a method.
  • Clean up with try-with-resources rather than finally when possible.

Reading a stack trace

Start at the top line: it names the exception type and message. The first frame below it that belongs to your own package is usually where to look. Lines starting with "Caused by" show the underlying reason.

Next steps

Learn data structures in the Collections Framework and functional processing in the Streams API. For object design see Java OOP concepts.