Course outline · 0% complete

0/29 lessons0%

Course overview →

Exceptions

lesson 8-2 · ~6 min · 23/29

When things go wrong

Real programs run on hostile input: files that are missing, network calls that time out, users who type "abc" where a number belongs. A server that dies on the first bad request is useless, so every serious codebase has a strategy for failure — and exceptions are Java's. They also carry a hard requirement into interviews and code review: you are expected to know what your code can throw.

An exception is an object thrown when an operation cannot proceed: dividing by zero, indexing past an array's end, parsing "abc" as a number. Uncaught, it kills the program with a stack trace. To handle it, use try/catch, Java's try/except:

try {
  int n = Integer.parseInt(input);
  System.out.println(n * 2);
} catch (NumberFormatException e) {
  System.out.println("not a number: " + e.getMessage());
} finally {
  System.out.println("runs either way");
}

The catch names the exception type it handles. e.getMessage() carries the details. finally runs whether or not anything was thrown, for cleanup like closing files. You can stack multiple catch blocks, most specific first.

Code exercise · java

Run this. The out-of-bounds access throws, the catch absorbs it, finally runs, and the program continues instead of dying.

Throwing, and checked vs unchecked

Your own code throws with throw:

static int divide(int a, int b) {
  if (b == 0) {
    throw new IllegalArgumentException("cannot divide by zero");
  }
  return a / b;
}

Java splits exceptions into two families:

  • Unchecked (subclasses of RuntimeException, like IllegalArgumentException, NullPointerException): programming bugs. Catch optional.
  • Checked (like IOException from file reading): expected outside failures. The compiler forces every caller to either catch it or declare throws IOException on its own signature and pass the problem up.

Python has no checked exceptions at all, so this compiler enforcement will be new to you. The reasoning: a missing file is not a bug in your code, it is a fact of the outside world — so the compiler refuses to let any caller simply forget that it can happen.

Reading a stack trace

When an exception goes uncaught, Java prints a stack trace: the exception's type and message, then the chain of method calls that was in progress, innermost first. Learning to read one is the highest-value debugging skill in Java, because it names the exact line that failed:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.divide(Main.java:7)
    at Main.main(Main.java:3)

Read it top down: what went wrong (ArithmeticException: / by zero), where (Main.java line 7, inside divide), and who called it (line 3 in main). The first line that mentions your own file is almost always where to look — lines from java.util... are the library doing its job of refusing bad input.

Quiz

A method calls a file-reading API that throws the checked IOException, but has no try/catch and no throws clause. What happens?

Code exercise · java

Your turn. Write static int divide(int a, int b) that throws IllegalArgumentException with the message `cannot divide by zero` when b is 0. In main, print divide(10, 2), then call divide(10, 0) inside a try/catch that prints `error: ` plus the exception's message.