Reading — step 1 of 7
Learn
Every program encounters errors. A user types "abc" where a number is expected. A file you need doesn't exist. A network request times out. A division by zero. You can't prevent all errors, but you can decide what happens when they occur. Python's exception handling — try and except — gives you a way to attempt something risky and catch the error if it fails.
The basic shape
When an error occurs inside try:
- Python looks for a matching
exceptblock. - If found, the except runs and the program continues.
- If not found, the exception propagates up — eventually crashing the program if no one handles it.
If NO error occurs in try, all except blocks are skipped.
Catching multiple types in one block
A single except can catch any of multiple types — pass them as a tuple.
Capturing the exception object
as e binds the exception object to a name. You can read its message, print a traceback, or re-raise it.
else and finally
elseruns only when no exception was raised intry. Useful for the "happy path."finallyalways runs. Use it for cleanup (closing files, releasing locks).
Common exception types you'll see
ValueError— wrong value (int("abc"))TypeError— wrong type ("a" + 1)KeyError— missing dict keyIndexError— list/string index out of rangeFileNotFoundErrorZeroDivisionErrorAttributeError—obj.missing_attrRuntimeError— generic catch-allException— base class of (almost) all the above
⚠️ Don't use bare except
Bare except catches EVERY exception including KeyboardInterrupt (Ctrl+C) and SystemExit. Worse, except: pass hides bugs — the program just silently does nothing wrong. Always catch the specific exception(s) you intend to handle:
EAFP — "Easier to Ask Forgiveness than Permission"
Python style prefers TRY-IT and handle errors over CHECK-FIRST:
Common mistakes
- Catching too broadly:
except:orexcept Exceptionhides bugs. Be specific. - Exception used for control flow when an
ifwould work — exceptions are for exceptional cases. - Empty except body that silently swallows — at minimum, log the error.
- Forgetting cleanup: if you open a file in
try, ALWAYS close it (usewithorfinally).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…