Programming with Java
Lesson 4 of 4 8 min +55 XP

Exceptions & Error Handling

Deal with things that go wrong.

What you'll learn

  • Explain what an exception is
  • Use try/catch/finally
  • Distinguish checked from unchecked exceptions
The tightrope safety net

A tightrope walker performs over a net so a slip doesn't end in disaster. Exception handling is that net for code — try the risky move, and if it fails, catch the error and recover gracefully instead of crashing.

Failing gracefully

An exception is an object representing a problem that disrupts normal flow — a missing file, a divide-by-zero, a bad index. In Java you wrap risky code in a try block, handle problems in catch, and put cleanup (like closing a file) in finally, which runs whether or not an exception occurred.

Checked vs. unchecked

Checked exceptions (e.g. IOException) must be declared or caught — the compiler enforces it. Unchecked exceptions (e.g. NullPointerException) extend RuntimeException and need no declaration.

try { readFile(); } catch (IOException e) { showError(e); } finally { closeStream(); } — cleanup always runs.
Lab · Where does cleanup go?
  1. You open a network connection, then parse data that might throw.
  2. Decide where to put the parsing and where to close the connection.
  3. Name the block that guarantees the close runs.

What you should see: Put the risky parse in try, handle failures in catch, and close the connection in finally so it runs whether parsing succeeds or throws.

Knowledge Check

+15 XP / correct

1. Code in a finally block runs…

2. A checked exception in Java must be…