Lesson 117 min read
Error Handling
When things go wrong — and they will — be ready
Why Errors Happen (And That's OK)
Errors are a normal part of programming — like potholes on a road. The question isn't "will I hit one?" but "am I ready when I do?" Python's error handling lets you catch problems gracefully instead of your program crashing and burning.
Python has two kinds of problems:
- Syntax errors — You typed something Python can't understand. Like a typo in a recipe:
prnt("hello"). Python catches these before running. - Exceptions — Your code is valid Python, but something went wrong at runtime: dividing by zero, opening a file that doesn't exist, accessing a list index that's out of range. When an exception is thrown, Python walks up the call stack looking for a handler.
Common Exceptions
Try / Except / Else / Finally
The try/except block is your safety net. Here's how the four parts work:
try— Put the risky code here. "Try this, and if it blows up..."except— "...catch the explosion and handle it." You can catch specific exception types or all of them.else— Runs ONLY iftrysucceeded with no errors. "If everything went well, do this too."finally— Runs NO MATTER WHAT — error or not. Perfect for cleanup. "Always do this when we're done."
The Full Try/Except Pattern
Raising Exceptions
Sometimes you want to raise an error on purpose. Maybe someone passed invalid data to your function, and you want to stop things early with a clear message. Use raise for this.
Raising & Custom Exceptions
Best Practices
Here are the golden rules of error handling:
- Be specific — Catch
ValueError, not bareexcept:. A bare except catches everything, including keyboard interrupts and system exits. That's almost never what you want. - Don't silence errors — Never write
except: pass. If something goes wrong, you want to know about it. - Use
else— Put success-only code inelse, not intry. This way you don't accidentally catch errors from the success code. - EAFP over LBYL — Python prefers "Easier to Ask Forgiveness than Permission." Try the operation and catch the error, rather than checking every possible condition first.
EAFP vs. LBYL
Note: Think of
try/except like a stunt double in a movie. You let the stunt double (try block) do the dangerous stuff, and if something goes wrong, the safety crew (except block) handles it — so the movie (your program) keeps rolling.Quick check
Continue reading