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 exceptions are and why they beat crashing
- try / catch / finally / throw
- Checked vs unchecked exceptions
- How to handle errors well (not swallow them)
- 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
Problems you’re expected to plan for — a missing file, a network error. Java forces you to handle or declare them.
Bugs — null pointer, index out of bounds, divide by zero. They mean “fix the code,” not “handle at runtime.”
Handle errors well
- Catch specific, not a blanket
catch (Exception e)that hides real bugs. - Never swallow — an empty catch block hides failures until they explode later.
- Clean up in finally (or try-with-resources) so files/connections always close.
- Fail with a clear message — “order 123 not found”, not a raw stack trace to the user.
Where you’ll use it — real life
The bank times out — you catch it and retry or mark it, instead of crashing (your EMV world).
A failed transaction throws — you catch and roll back.
Bad input shouldn’t take the app down — catch and return a 400.
finally guarantees connections close even when things fail.
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 →