Tutorials / Java: From Zero to Advanced / Exceptions: checked, unchecked and try-with-resources

Exceptions: checked, unchecked and try-with-resources

14 min read java
Course contents (20 lessons)
  1. Getting started
  2. Installing JDK 21 and running Java code
  3. Your first program: how a Java file is built
  4. Language basics
  5. Variables and data types
  6. Strings, formatting and text blocks
  7. Control flow: if, switch expressions and loops
  8. Data and methods
  9. Arrays and the collections framework
  10. Methods, overloading and varargs
  11. Object-oriented Java
  12. Classes, objects and encapsulation
  13. Inheritance, abstract classes and interfaces
  14. Records, enums and sealed types
  15. Writing robust code
  16. Exceptions: checked, unchecked and try-with-resources
  17. Generics, bounded types and wildcards
  18. Files and the NIO.2 API
  19. Modern Java
  20. Lambdas and the Stream API
  21. Optional: handling missing values
  22. Concurrency: executors, CompletableFuture and virtual threads
  23. Tools, services and the final project
  24. Maven and Gradle basics
  25. Testing with JUnit 5
  26. A small REST service with the JDK HTTP server
  27. Final project: a library manager

What an exception is

When something goes wrong at runtime, such as a missing file, text that is not a number or a call on null, Java creates an exception object and throws it. The method stops, and the exception travels up the call stack until some code catches it. If nothing catches it, the program ends and prints a stack trace.

Two families

All exceptions descend from Throwable. The two branches below it matter most.

  • Checked exceptions extend Exception but not RuntimeException. The compiler forces you to either catch them or declare them with throws. IOException is the typical example. They represent problems a caller can reasonably be expected to handle.
  • Unchecked exceptions extend RuntimeException. The compiler does not force you to handle them. NullPointerException, IllegalArgumentException and ArrayIndexOutOfBoundsException are of this kind. They usually indicate a bug in the code.

There is also Error, for serious JVM problems such as OutOfMemoryError. You do not normally catch those.

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

public class Main {

    public static void main(String[] args) {
        // 1. try / catch / finally
        for (String input : new String[]{"42", "abc", ""}) {
            try {
                int number = Integer.parseInt(input);
                System.out.println("Parsed " + number + ", 100 / number = " + (100 / number));
            } catch (NumberFormatException e) {
                System.out.println("Not a number: '" + input + "'");
            } finally {
                System.out.println("Checked " + input.length() + " characters");
            }
        }

        // 2. Custom checked exception
        try {
            withdraw(500, 800);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage() + " (short by " + e.getShortfall() + ")");
        }

        // 3. Multi-catch and wrapping the cause
        try {
            loadConfig("timeout=abc");
        } catch (ConfigException e) {
            System.out.println(e.getMessage() + " <- " + e.getCause().getClass().getSimpleName());
        }

        // 4. try-with-resources closes in reverse order, even after an exception
        try (Resource first = new Resource("first");
             Resource second = new Resource("second")) {
            System.out.println("Using resources");
            throw new IllegalStateException("boom");
        } catch (IllegalStateException e) {
            System.out.println("Caught " + e.getMessage());
        }

        // 5. Fail fast with unchecked exceptions
        try {
            setAge(-5);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

    static class InsufficientFundsException extends Exception {
        private final double shortfall;

        InsufficientFundsException(double shortfall) {
            super("Not enough money in the account");
            this.shortfall = shortfall;
        }

        double getShortfall() { return shortfall; }
    }

    static void withdraw(double balance, double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount - balance);
        }
    }

    static class ConfigException extends Exception {
        ConfigException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    static int loadConfig(String line) throws ConfigException {
        try {
            String[] parts = line.split("=");
            return Integer.parseInt(parts[1]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            throw new ConfigException("Bad configuration line: " + line, e);
        }
    }

    static class Resource implements AutoCloseable {
        private final String name;

        Resource(String name) {
            this.name = name;
            System.out.println("Open " + name);
        }

        @Override
        public void close() {
            System.out.println("Close " + name);
        }
    }

    static void setAge(int age) {
        if (age < 0 || age > 130) {
            throw new IllegalArgumentException("age out of range: " + age);
        }
    }
}

Walking through it

The first loop feeds three inputs through Integer.parseInt. For "42" everything works. For "abc" and the empty string, NumberFormatException is thrown and caught. The finally block runs every time, with or without an exception. Look at the output carefully: the line "Checked 2 characters" appears after the success as well. Use finally for cleanup that must always happen. Since Java 7, try-with-resources is the preferred way for that purpose.

The custom InsufficientFundsException extends Exception, so it is checked. The method declares throws InsufficientFundsException, and the caller must handle it. The exception carries data, the shortfall, as well as the message. Whether to make a custom exception checked or unchecked is a long-running debate. My own rule: checked for conditions that a caller can recover from and that are part of the method's normal contract, unchecked for programming errors. Many modern libraries use unchecked exceptions almost everywhere, because checked ones make lambdas and layers of code noisy.

In loadConfig, one catch handles two exception types with |. We then throw a different exception, ConfigException, and pass the original as the cause. Wrapping like this lets each layer speak in its own terms without losing the original stack trace. When the trace is printed, you see "Caused by". Never throw away the cause.

The try-with-resources statement declares resources in brackets. Anything that implements AutoCloseable qualifies. The output shows that both resources are closed in reverse order, "second" before "first", before the catch block runs, even though the body threw an exception. Use it for files, streams, database connections and anything with a close method. Writing manual finally blocks for this is old style and easy to get wrong.

Finally, setAge validates its argument and throws IllegalArgumentException early. Failing at the point of the mistake makes bugs much easier to find than letting a bad value travel through the program.

Rules I follow

  • Catch the most specific exception you can handle. Do not catch Exception or Throwable broadly unless you are at the top of the program or a request.
  • Never leave a catch block empty. At minimum, log the exception.
  • Log or handle an exception once. Logging and then rethrowing at every layer fills the log with duplicates.

Common mistakes

  • Swallowing exceptions with an empty catch.
  • Catching Exception and printing only e.getMessage(). You lose the stack trace.
  • Forgetting to pass the cause when wrapping.

Try it yourself

  1. Write a method parsePositive(String text) that throws IllegalArgumentException with a clear message for non-numbers and for zero or negative values.
  2. Create a custom checked exception OutOfStockException and use it in a method buy(String item, int qty).
  3. Write a resource class that fails in its constructor for the second resource, and observe which resources get closed.
java
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        // 1. try / catch / finally
        for (String input : new String[]{"42", "abc", ""}) {
            try {
                int number = Integer.parseInt(input);
                System.out.println("Parsed " + number + ", 100 / number = " + (100 / number));
            } catch (NumberFormatException e) {
                System.out.println("Not a number: '" + input + "'");
            } finally {
                System.out.println("Checked " + input.length() + " characters");
            }
        }

        // 2. Custom checked exception
        try {
            withdraw(500, 800);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage() + " (short by " + e.getShortfall() + ")");
        }

        // 3. Multi-catch and wrapping the cause
        try {
            loadConfig("timeout=abc");
        } catch (ConfigException e) {
            System.out.println(e.getMessage() + " <- " + e.getCause().getClass().getSimpleName());
        }

        // 4. try-with-resources closes in reverse order, even after an exception
        try (Resource first = new Resource("first");
             Resource second = new Resource("second")) {
            System.out.println("Using resources");
            throw new IllegalStateException("boom");
        } catch (IllegalStateException e) {
            System.out.println("Caught " + e.getMessage());
        }

        // 5. Fail fast with unchecked exceptions
        try {
            setAge(-5);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

    static class InsufficientFundsException extends Exception {
        private final double shortfall;

        InsufficientFundsException(double shortfall) {
            super("Not enough money in the account");
            this.shortfall = shortfall;
        }

        double getShortfall() { return shortfall; }
    }

    static void withdraw(double balance, double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount - balance);
        }
    }

    static class ConfigException extends Exception {
        ConfigException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    static int loadConfig(String line) throws ConfigException {
        try {
            String[] parts = line.split("=");
            return Integer.parseInt(parts[1]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            throw new ConfigException("Bad configuration line: " + line, e);
        }
    }

    static class Resource implements AutoCloseable {
        private final String name;

        Resource(String name) {
            this.name = name;
            System.out.println("Open " + name);
        }

        @Override
        public void close() {
            System.out.println("Close " + name);
        }
    }

    static void setAge(int age) {
        if (age < 0 || age > 130) {
            throw new IllegalArgumentException("age out of range: " + age);
        }
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account