Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Fundamentals of Object Oriented Programming Level Two · Lesson 5 of 8

Module Four

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
5
Module 4: Exception Handling & Robust Objects for Young Coders
⭐ Module 4 · Level Two

Exception Handling &
Robust Objects

🛡️ Catch problems before they crash your program

🎯 What you'll learn in this module

  • ✔ The difference between checked and unchecked exceptions
  • ✔ How to use try / catch / finally and manage resources cleanly
  • ✔ How to create your own custom exception classes
  • ✔ How to design an exception hierarchy for your app
  • ✔ The difference between fail‑fast and fail‑safe strategies
  • ✔ How to validate object state in constructors so bad objects can't exist
💥
What Is an Exception?
The Big Idea

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).

🚨 An exception is like a fire alarm: something's wrong, and everyone needs to react. Handling it well means evacuating calmly — ignoring it means the building burns down.
⚖️
Checked vs. Unchecked Exceptions
Classification

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
🏥 Checked = a scheduled doctor's appointment (you know it's coming). Unchecked = an unexpected bump in the road (you hope to avoid it).
🪤
Try / Catch / Finally
Tool

This trio is the heart of exception handling:

🟢 try
→
Run risky code
🔴 catch
→
Handle the error
🔵 finally
→
Always runs — cleanup!

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.

🎪 A circus trapeze act: try = the performance, catch = the safety net, finally = cleaning up after the show.
📛
Custom Exception Classes
Design

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.

📦 Delivery companies have specific labels: "fragile," "keep cold," "return to sender." Custom exceptions are the specific labels of your domain.
🌳
Designing an Exception Hierarchy
Design

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.

🐕 A family tree of dogs: you can point at "my dog Rex" (specific), "all golden retrievers" (a group), or "all dogs" (the base). Same idea, different granularity.
🚦
Fail‑Fast vs. Fail‑Safe
Strategy

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.

✈️ A plane has fail‑fast checks (if the engine is broken, abort takeoff) and fail‑safe systems (if a screen fails, another one takes over).
🚧
Validating Object State in Constructors
Best Practice

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.

🏗️ A factory checks every part before assembly. If a bolt is cracked, it never reaches the finished car.
⚠️ Common trap: Catching every exception with a bare catch (Exception e) {} and doing nothing is worse than crashing. It hides bugs, silences alarms, and makes debugging a nightmare. Catch the exceptions you can actually handle, and let the rest propagate.

🛠️ Hands-on activities (no boring stuff!)

1

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.

2

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.

3

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.

4

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.

5

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.

6

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.

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→