An exception is a signal that something went wrong while your program is running. Maybe a file wasn't found, a number was divided by zero, or a user typed nonsense into a field.
Without exception handling, a single mistake crashes the whole program. With it, you can catch the error, decide what to do, and keep going (or exit gracefully with a helpful message).
Languages like Java split exceptions into two families:
| Type | Checked | Unchecked |
|---|---|---|
| When checked? | At compile time | At runtime |
| Must you handle it? | Yes — compiler forces you | No — you can choose |
| Typical examples | File not found, network errors | Null pointer, divide by zero, bad index |
| Best for… | Things you can recover from | Programming mistakes |
This trio is the heart of exception handling:
try holds the risky code. catch handles the error if one occurs. finally runs no matter what — perfect for closing files, disconnecting from databases, or logging.
Built‑in exceptions cover common problems, but sometimes your app has its own specific errors. That's when you write a custom exception — a class that extends the base exception class and carries the right name and message.
Example: InsufficientBalanceException is more meaningful than a generic RuntimeException. It tells callers exactly what went wrong — and lets them catch it specifically. Good custom exceptions read like plain English.
When your app has many errors, group them into a hierarchy: a base exception like AppException, and subclasses like ValidationException, PaymentException, and NetworkException.
This lets callers catch errors at the right level of detail: catch (PaymentException e) for the exact case, or catch (AppException e) when you just want a general safety net.
When something goes wrong, you have two main strategies:
Fail‑fast: throw an exception immediately, so the bug is caught early. Best for programming mistakes and invalid input — you want the problem loud and clear.
Fail‑safe: catch the error, log it, and continue with a fallback (like a default value or a cached result). Best for non‑critical features — a weather widget failing shouldn't crash the whole app.
The best time to catch a bad object is before it exists. In a constructor, check every required argument: is the age positive? Is the email well‑formed? Is the price not negative?
If validation fails, throw an IllegalArgumentException or your custom exception before creating the object. The result: every object in your system is guaranteed valid. That's a superpower — bugs have fewer places to hide.
Divide-by-zero lab: Write a method that divides two numbers. Call it with a zero divisor inside a try/catch. Print a friendly message in the catch block, then verify the program keeps running.
Always cleanup: Write a try/finally block where the try throws an error. In the finally, print "cleanup done." Confirm it runs even when the try fails.
Custom exception: Build a BankAccount class with a withdraw() method. If the balance is too low, throw your own InsufficientFundsException. Catch it in a test.
Exception hierarchy: Create a base AppException and two subclasses: InputException and SystemException. Try catching each one specifically, then all of them together at the base.
Fail-fast constructor: Write a Student class that throws an exception if age is negative or the name is empty. Try creating invalid students and confirm the error is thrown immediately.
Fail-safe vs. fail-fast: Build a simple app with two buttons: "Load Weather" (fail‑safe — default message if it fails) and "Load Balance" (fail‑fast — throw an exception if data missing). Decide why each choice fits.
By the end of this module, you'll be able to: explain checked vs. unchecked exceptions, write clean try/catch/finally blocks, create custom exceptions, design an exception hierarchy, and validate object state so broken objects can't exist.