Java Exceptions: Checked vs Unchecked, try-catch-finally and try-with-resources

admin5 min read
In this tutorial
  1. What is an exception?
  2. The exception hierarchy
  3. Checked vs unchecked
  4. try, catch and finally
  5. try-with-resources
  6. Throwing exceptions
  7. Custom exceptions
  8. Wrapping exceptions without losing the cause
  9. Best practices
  10. Summary

Things go wrong in real programs: files are missing, networks drop, users type letters where numbers belong. Java’s exception system lets you separate the normal flow of your code from the handling of those problems. Used well, it makes programs robust. Used badly, it hides bugs.

This tutorial explains how exceptions work, the difference between checked and unchecked exceptions, and the habits that separate professional error handling from beginner code.

What is an exception?

An exception is an object that represents an unexpected event. When something goes wrong, Java throws an exception. Execution stops at that point and jumps to the nearest matching catch block. If nothing catches it, the program crashes and prints a stack trace.

int[] scores = {90, 80};
System.out.println(scores[5]); // throws ArrayIndexOutOfBoundsException

The exception hierarchy

All exceptions extend Throwable, which has two main branches:

  • Error: serious problems with the JVM itself, such as OutOfMemoryError or StackOverflowError. You normally do not catch these.
  • Exception: problems your program can reasonably handle. This branch splits again:
  • Checked exceptions: subclasses of Exception that are not RuntimeException, for example IOException, SQLException and InterruptedException.
  • Unchecked exceptions: subclasses of RuntimeException, for example NullPointerException, IllegalArgumentException, ArithmeticException and IndexOutOfBoundsException.

Checked vs unchecked

Checked exceptions are checked by the compiler. If a method can throw one, you must either catch it or declare it with throws. They represent conditions outside your program’s control that a caller should be ready for: a missing file, a failed network call.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

String readConfig(Path path) throws IOException {   // must declare or catch
    return Files.readString(path);
}

Unchecked exceptions are not checked by the compiler. They usually signal programming errors: calling a method on null, passing an invalid argument, dividing by zero. The fix is normally to correct the code, not to catch the exception.

A useful rule of thumb: if the caller can do something sensible to recover, a checked exception may make sense. If the only fix is to change the code, use an unchecked exception.

Many modern libraries (including Spring) favour unchecked exceptions, because forcing every layer to declare or catch checked exceptions tends to produce boilerplate.

try, catch and finally

public class ParseAge {
    static int parseAge(String input) {
        try {
            int age = Integer.parseInt(input.trim());
            if (age < 0 || age > 150) {
                throw new IllegalArgumentException("Age out of range: " + age);
            }
            return age;
        } catch (NumberFormatException e) {
            System.out.println("Not a number: '" + input + "'");
            return -1;
        } finally {
            System.out.println("Finished parsing '" + input + "'");
        }
    }

    public static void main(String[] args) {
        System.out.println(parseAge("27"));
        System.out.println(parseAge("twenty"));
    }
}

Output:

Finished parsing '27'
27
Not a number: 'twenty'
Finished parsing 'twenty'
-1
  • The try block contains code that might fail.
  • A catch block runs only if a matching exception is thrown.
  • The finally block always runs, whether or not an exception happened, even after return. It is traditionally used for clean-up.

Catching several exceptions

Order catch blocks from most specific to most general, or combine unrelated ones with |:

try {
    process(file);
} catch (FileNotFoundException e) {
    System.out.println("File missing: " + e.getMessage());
} catch (IOException | SecurityException e) {
    System.out.println("Could not read file: " + e.getMessage());
}

FileNotFoundException is a subclass of IOException, so it must come first, or the compiler reports it as unreachable.

try-with-resources

Files, database connections and network sockets must be closed after use, even if an error happens. Before Java 7 this meant messy finally blocks. Now, any object that implements AutoCloseable can be declared in a try-with-resources statement and Java closes it for you:

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CountLines {
    public static void main(String[] args) {
        Path path = Path.of("students.csv");
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            long lines = reader.lines().count();
            System.out.println("Lines: " + lines);
        } catch (IOException e) {
            System.out.println("Could not read " + path + ": " + e.getMessage());
        }
    }
}

The reader is closed automatically when the block ends, in every case. You can declare several resources separated by semicolons; they are closed in reverse order.

Throwing exceptions

Use throw to signal that something is wrong, ideally as early as possible:

public void withdraw(double amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("Amount must be positive, got " + amount);
    }
    if (amount > balance) {
        throw new IllegalStateException("Insufficient funds");
    }
    balance -= amount;
}

Reuse standard exceptions where they fit:

  • IllegalArgumentException: a parameter has an invalid value.
  • IllegalStateException: the object is not in the right state for this call.
  • NullPointerException (via Objects.requireNonNull): a required value is null.
  • UnsupportedOperationException: the operation is not supported.

Custom exceptions

Create your own exception when callers need to recognise and handle a specific business problem:

public class InsufficientFundsException extends RuntimeException {
    private final double shortfall;

    public InsufficientFundsException(double shortfall) {
        super("Insufficient funds: short by " + shortfall);
        this.shortfall = shortfall;
    }

    public double getShortfall() {
        return shortfall;
    }
}

Extend RuntimeException for an unchecked exception, or Exception for a checked one.

Wrapping exceptions without losing the cause

When you catch a low-level exception and throw a higher-level one, always pass the original as the cause:

try {
    return repository.load(id);
} catch (SQLException e) {
    throw new DataAccessException("Could not load customer " + id, e);
}

The stack trace will then show both exceptions, with “Caused by:”, which is essential for debugging.

Best practices

  • Never swallow exceptions. An empty catch (Exception e) { } hides problems and makes bugs nearly impossible to find. At the very least, log the error.
  • Catch specific exceptions, not Exception or Throwable, unless you are at the very top of the application.
  • Do not use exceptions for normal control flow. Check map.containsKey instead of catching a NullPointerException.
  • Write helpful messages that include the bad value: “Age out of range: -4” beats “Invalid input”.
  • Clean up with try-with-resources, not manual finally blocks.
  • Fail fast. Validate arguments at the start of a method, so errors appear close to their cause.

Summary

  • Exceptions extend Throwable; Error is for JVM problems, Exception for program problems.
  • Checked exceptions must be caught or declared; unchecked ones (RuntimeException) usually indicate bugs.
  • finally always runs; try-with-resources closes resources automatically.
  • Throw early with clear messages, reuse standard exceptions, and always keep the original cause.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *