Java · Core APIs

Exception Handling

Exceptions signal that something went wrong. Handling them well keeps programs stable and errors understandable.

Intermediate 5 min Lesson 17 of 31Examples target Java 21 LTS (they also run on Java 25).
Before you start:Classes and Objects
0/31 in Java
On this page · 5 min · Intermediate

In simple words#

try/catch is a safety net under a trapeze. If the performer slips (an exception), the net catches them and the show continues instead of ending in disaster.

Checked exception
Must be caught or declared (IOException).
Unchecked exception
RuntimeException subclasses (NullPointerException).
try-with-resources
Automatically closes files and connections.

Learning objectives#

  • Catch and handle exceptions
  • Distinguish checked and unchecked
  • Throw and declare exceptions
  • Close resources automatically

Explanation#

try { risky } catch (SpecificException e) { handle } finally { always runs }.

Checked exceptions (IOException, SQLException) must be caught or declared with throws. Unchecked ones (extend RuntimeException) usually mean programming errors.

throw new IllegalArgumentException("...") signals invalid input. Custom exceptions express business problems.

try (var reader = …) { } closes resources automatically, even on errors.

Code example: Safe file reading and a custom exception#

JavaSafe file reading and a custom exception Illustrative
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


class InsufficientStockException extends RuntimeException {
    InsufficientStockException(String product) { super("Not enough stock for " + product); }
}


public class Errors {
    static void reserve(String product, int stock, int qty) {
        if (qty > stock) throw new InsufficientStockException(product);
    }


    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("prices.txt"))) {
            System.out.println(reader.readLine());
        } catch (IOException e) {
            System.out.println("Could not read prices: " + e.getMessage());
        }


        try {
            reserve("Laptop", 2, 5);
        } catch (InsufficientStockException e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("Reservation check finished");
        }
    }
}
Expected output
Could not read prices: prices.txt (No such file or directory)
Not enough stock for Laptop
Reservation check finished

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. try-with-resources closes the reader automatically.
  2. IOException (checked) is caught with a friendly message.
  3. A custom unchecked exception signals a business rule.
  4. finally always runs.

Real-world use case#

An order service throws InsufficientStockException, which the API layer turns into HTTP 409 Conflict.

Common mistakes#

Empty catch blocks

Swallowing exceptions hides bugs. At least log them.

Catching Exception everywhere

Catch specific types you can handle; let others propagate.

Best practices#

  • Catch specific exceptions
  • try-with-resources for files and connections
  • Meaningful messages
  • Log once, at the boundary

Remember this#

try → catch → finally.

Checked must be handled or declared.

try-with-resources closes automatically.

Practice exercise#

Your task: Parse "abc" with Integer.parseInt and print "Invalid number" instead of crashing.

Show solution
Java Illustrative
try {
    int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Invalid number");
}

Mini quiz#

Exception Handling quizMultiple choice Question 1 of 1

Which statement closes resources automatically?

Score so far: 0/0

Want more? Practise all Java MCQs · Java interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.