Skip to content
Codewilds

Lesson 31 of 34 · Collections & Exceptions

Java Exceptions: try, catch, finally and Custom Exceptions

medium20 XP3 min read

Programs live in a messy world: users type "twelve" where a number belongs, files go missing, accounts run dry. Java reports problems like these with exceptions — objects that describe what went wrong and travel up the call stack until some code handles them.

When an exception is thrown

Any method can signal a problem by throwing an exception:

static void withdraw(int amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException("amount must be positive");
    }
    // ...
}

throw stops the method immediately. If no code catches the exception, the program crashes and prints it, followed by a stack trace — the chain of method calls that led there, with line numbers:

Exception in thread "main" java.lang.IllegalArgumentException: amount must be positive

try, catch and finally

Wrap risky code in try and handle the problem in catch:

try {
    int level = Integer.parseInt("12abc");
    System.out.println("Level " + level);
} catch (NumberFormatException e) {
    System.out.println("That is not a number!");
} finally {
    System.out.println("Done.");
}
That is not a number!
Done.

The moment parseInt throws, Java skips the rest of the try block and jumps to the matching catch. The finally block runs no matter what — exception or not, even after a return — so it is the place for clean-up. You can have several catch blocks (most specific first), or catch several types at once: catch (NumberFormatException | NullPointerException e).

The exception family

Throwable
├── Error                     serious JVM problems (StackOverflowError) – don't catch
└── Exception                 checked: must be caught or declared
    └── RuntimeException      unchecked: bugs and bad arguments
        ├── NullPointerException
        ├── IllegalArgumentException
        │   └── NumberFormatException
        ├── IllegalStateException
        └── IndexOutOfBoundsException

Unchecked exceptions (RuntimeException and its children) usually mean a bug or invalid input; you may catch them, but you don't have to. Checked exceptions — every other Exception — represent problems a caller should plan for. The compiler forces you to either catch them or declare them with throws:

static String loadSave(String file) throws java.io.IOException { /* ... */ }

Forget both and the code will not compile: unreported exception IOException; must be caught or declared to be thrown.

Custom exceptions

Your own exception is just a class that extends Exception (checked) or RuntimeException (unchecked). It can carry extra information:

class OutOfManaException extends Exception {
    private final int missing;

    OutOfManaException(int missing) {
        super("not enough mana: missing " + missing);
        this.missing = missing;
    }

    int getMissing() {
        return missing;
    }
}

super(message) hands the message to Exception, so getMessage() returns it. When you convert one exception into another, pass the original as the cause — throw new SaveFailedException("could not save", e); — so the full story is kept.

Objects that must be closed (files, connections) belong in try-with-resources: try (var reader = openReader()) { ... } closes reader automatically, even when an exception flies.

Common mistakes

  • Swallowing exceptions: an empty catch (Exception e) { } hides bugs. Handle the problem, or let it propagate.
  • Catching too broadly: catch (Exception e) also catches the bugs you didn't expect. Catch the specific type.
  • Wrong catch order: a catch (Exception e) before catch (NumberFormatException e) does not compile — the second one could never run.
  • Exceptions as normal control flow: check if (map.containsKey(key)) rather than waiting for something to blow up.

Assignment

  1. In Main, implement parseOrDefault(String text, int fallback): return the whole number in text (ignore spaces around it), or fallback when text is null or not a valid int. parseOrDefault(" -15 ", 0) → -15, parseOrDefault("12abc", 7) → 7
  2. Complete the checked exception InsufficientFundsException: its constructor takes the shortfall, its message is "insufficient funds: short by <shortfall>" and getShortfall() returns the shortfall.
  3. Complete Account:
    • deposit(int amount) adds to the balance; if amount <= 0 it throws IllegalArgumentException with the message "amount must be positive".
    • withdraw(int amount) throws the same IllegalArgumentException for amount <= 0, throws InsufficientFundsException(amount - balance) when amount is larger than the balance, and otherwise subtracts it. A failed call never changes the balance.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Errors and exceptions in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Lesson 31 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.