Career OS

Learn · OOP & Java

Exceptions & Error Handling

Things go wrong — a file’s missing, the network drops, a number won’t parse. Exceptions let your program deal with it instead of just dying.

Before we start

📋 What you’ll learn
  • What exceptions are and why they beat crashing
  • try / catch / finally / throw
  • Checked vs unchecked exceptions
  • How to handle errors well (not swallow them)
✅ After this you’ll be able to
  • Wrap risky code and recover gracefully
  • Explain checked vs unchecked
  • Avoid the classic error-handling mistakes

Why you’re learning it: real systems fail constantly; handling failure well is what separates hobby code from production code — and it’s asked in interviews. ⏱️ ~20 min.

The idea — a safety net

An exception is the program saying “something went wrong here” and jumping to your plan B instead of crashing. You wrap risky code in try, handle the problem in catch, and clean up in finally.

try {
    int x = Integer.parseInt(input);   // might fail
} catch (NumberFormatException e) {
    // plan B: tell the user it wasn't a number
} finally {
    // always runs — close files, release locks
}

Checked vs unchecked

✅ Checked

Problems you’re expected to plan for — a missing file, a network error. Java forces you to handle or declare them.

⚠️ Unchecked

Bugs — null pointer, index out of bounds, divide by zero. They mean “fix the code,” not “handle at runtime.”

Handle errors well

Where you’ll use it — real life

🌐 API calls

The bank times out — you catch it and retry or mark it, instead of crashing (your EMV world).

🗄️ Database

A failed transaction throws — you catch and roll back.

📥 User input

Bad input shouldn’t take the app down — catch and return a 400.

🧹 Cleanup

finally guarantees connections close even when things fail.

🗣️ The 2-minute explain test

Out loud: “What do try/catch/finally do, and what’s the difference between checked and unchecked exceptions?” Log it in your Journal.


Next: Generics →

Saves your progress on this device.