Skip to content

Intermediate · Exceptions and generics · topic 26 of 60 · 25 min

Exceptions: try, catch and finally

Explanation

An exception is an object that signals a problem and interrupts normal flow. try wraps code that may fail, catch handles a specific exception type, and finally always runs for clean-up. All exceptions descend from Throwable: Error (serious JVM problems, do not catch) and Exception (problems your program can handle). Catch the most specific types first.

What happens when something fails

When code hits a problem, such as dividing by zero or reading a missing file, Java creates an exception object and throws it. The current method stops; the exception travels back up the call stack until a matching catch block handles it. If nothing catches it, the thread dies and the stack trace is printed.

java
static int perHead(int total, int people) {
    return total / people;               // ArithmeticException when people is 0
}

public static void main(String[] args) {
    try {
        System.out.println(perHead(1200, 4));   // 300
        System.out.println(perHead(1200, 0));   // throws
        System.out.println("not reached");
    } catch (ArithmeticException e) {
        System.out.println("Cannot split: " + e.getMessage());   // / by zero
    } finally {
        System.out.println("Bill split done");   // always runs
    }
}

The exception hierarchy

output
Throwable
├── Error                         (OutOfMemoryError, StackOverflowError: do not catch)
└── Exception
    ├── IOException, SQLException…      (checked: must be handled or declared)
    └── RuntimeException                (unchecked)
        ├── NullPointerException
        ├── IllegalArgumentException
        ├── ArithmeticException
        └── IndexOutOfBoundsException…

Several catch blocks and multi-catch

java
try {
    int qty = Integer.parseInt(input);
    int[] stock = new int[5];
    stock[qty] = 1;
} catch (NumberFormatException e) {
    System.out.println("Quantity must be a number");
} catch (ArrayIndexOutOfBoundsException | NegativeArraySizeException e) {   // multi-catch
    System.out.println("No such shelf: " + e.getMessage());
}

Java checks catch blocks from top to bottom and runs the FIRST one whose type matches. A catch for a parent type placed before a catch for its child type makes the child catch unreachable, which is a compile error ("exception … has already been caught"). So order catch blocks from most specific to most general.

finally

finally runs after try (and catch), whether an exception happened or not, and even if the try block returns. Use it for clean-up, such as releasing a lock or closing a resource (though try-with-resources, topic 3, is better for closing). Never put return in finally: it silently overrides the try's return and swallows exceptions.

java
static int test() {
    try {
        return 1;
    } finally {
        System.out.println("finally runs");   // printed before the method returns 1
    }
}
Careful: catch (Exception e) {} with an empty body hides every problem, including bugs you did not expect, and the program continues with wrong data. At minimum log the exception; better, catch only what you can handle and let the rest propagate.

Useful methods on exceptions

  • getMessage(): the human-readable message.
  • printStackTrace(): prints the full stack trace (use a logger in real apps).
  • getCause(): the underlying exception, if this one wraps another.
Think of it like this: Exceptions are like the emergency chain in an Indian train. When something goes wrong, someone pulls the chain (throw), the train stops its normal journey, and the guard (the nearest matching catch) comes to handle it. Whatever happens, the cleaning crew at the next station (finally) still does its job.
Tip: Catch an exception only where you can do something meaningful: show a message, retry, use a default. Otherwise let it travel up to a central handler.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Exceptions: try, catch and finally · 1/6

Exceptions

In this lesson you will handle errors with exceptions.

Prefer a video by a teacher? Find free videos on “java exception handling try catch finally hierarchy” on YouTube ↗

In real life: Importing a bank statement

A finance app imports a CSV statement line by line. A bad line (a non-numeric amount) throws NumberFormatException; the importer catches it for that line, records the line number, and continues with the rest instead of failing the whole import.

java
String[] lines = {"2026-01-02,1500", "2026-01-03,abc", "2026-01-05,-200"};
int ok = 0;
java.util.List<String> bad = new java.util.ArrayList<>();
for (int i = 0; i < lines.length; i++) {
    try {
        double amount = Double.parseDouble(lines[i].split(",")[1]);
        ok++;
    } catch (NumberFormatException e) {
        bad.add("line " + (i + 1));
    }
}
System.out.println(ok + " imported, skipped " + bad);   // 2 imported, skipped [line 2]

Practice (0/3 done)

Task 1 · Question

What does this print? try { System.out.print("A"); int x = 5 / 0; System.out.print("B"); } catch (ArithmeticException e) { System.out.print("C"); } finally { System.out.print("D"); }

Task 2 · Question

Why does this NOT compile? try { … } catch (Exception e) { … } catch (NumberFormatException e) { … }

Task 3 · Practice

Write a program that asks for the number of people and a bill amount (as text), and prints the share per person. Handle NumberFormatException (not a number) and ArithmeticException (0 people) with separate friendly messages, and print "Thank you" in finally.

Quick quiz

Question 1

1.Which should you normally NOT catch?

Question 2

2.When does finally run?

Question 3

3.What does catch (A | B e) mean?

Question 4

4.What happens to an exception nobody catches in main?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which should you normally NOT catch?

Answer: OutOfMemoryError

Errors signal serious JVM problems.

When does finally run?

Answer: Always, even after return

finally always runs (except if the JVM exits).

What does catch (A | B e) mean?

Answer: One block that handles either A or B

Multi-catch handles several unrelated types in one block.

What happens to an exception nobody catches in main?

Answer: The thread ends and the stack trace is printed

Uncaught exceptions end the thread.

What happens to an exception that nobody catches?Related

Answer: The program crashes and shows the error

Unhandled exceptions end the process.

From Exceptions: try, catch, finally and custom exceptions

When does finally run?Related

Answer: Always, after try (and catch)

finally runs in every case, even after return.

From Error handling: try, catch, finally and throw

When does the else block of a try statement run?Related

Answer: Only when the try block raised no exception

else runs only on success. finally is the block that runs every time.

From Errors and exceptions

Which base class should your own exception types usually derive from?Related

Answer: std::exception (often via std::runtime_error)

Then generic handlers for std::exception catch them too, and what() works.

From Exceptions: throw, try, catch and noexcept

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Exceptions and generics” before its exam: Checked vs unchecked exceptions and throwing your own, try-with-resources and clean-up, Generics, Avoiding NullPointerException.
  2. Module 6 exam: Exceptions and generics · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, The collections framework. 60 topics left in the course before the final exam.

← Previous: Packages and access modifiers