Module 12 · Exception Handling — topic 11 of 11
Best practices
Writing exception handling that helps rather than hides: catching specific errors, never silencing bugs, EAFP versus LBYL, cleaning up with with/finally, handling errors at the right level, and useful messages.
Learning objectives
- Avoid the most damaging exception-handling mistakes
- Choose between EAFP and LBYL
- Decide where in a program errors should be handled
Definition
Exception-handling best practices are the habits that keep error handling precise, honest and maintainable: catch what you can handle, let the rest propagate, clean up reliably and report clearly.
Introduction
Bad exception handling is worse than none: a bare except: pass can hide a typo for months. A few habits keep error handling working for you.
Why it matters
Good handling makes failures obvious and recoverable; poor handling makes them invisible and expensive to debug.
Detailed explanation
Catch specific exceptions. except Exception or a bare except hides unrelated bugs such as NameError from typos.
Never silently swallow errors. If you deliberately ignore one, say so clearly — contextlib.suppress(FileNotFoundError) documents the intent.
EAFP ('easier to ask forgiveness than permission') tries the operation and handles failure; LBYL ('look before you leap') checks first. Python favours EAFP when failure is rare or checks would race, such as a file disappearing between the check and the open.
Handle errors where you can do something meaningful: retry, use a default, ask again, or report to the user. Low-level functions often should just raise; the program's boundary (main function, request handler) decides how to report.
Always release resources with with statements or finally.
Write messages that include the offending value and context, and chain translated errors with raise ... from.
Don't use exceptions for ordinary control flow when a simple if or dict.get is clearer.
Syntax
- Specific types only.
- Make intentional ignores explicit.
- Handle errors where you can act.
Code examples
A bare except hides a bug
0 12
EAFP and LBYL
0 0 0
More examples
Intentional ignores and a safe boundary
missing file ignored on purpose
{'ratio': 2.5, 'parse': "failed: invalid literal for int() with base 10: 'x1'", 'div': 'failed: division by zero'}Step-by-step explanation
- suppress makes it obvious that a missing file is expected and harmless.
- run_tasks is a boundary: it records expected failures per task so one failure doesn't stop the others.
- Unexpected exception types would still propagate, revealing real bugs.
Expected output
Running “Intentional ignores and a safe boundary” prints exactly:
Practical applications
- Web frameworks convert uncaught exceptions into 500 responses and log them.
- Batch jobs record failed items and continue.
Best practices
- Catch specific exceptions and do something meaningful.
- Let unexpected errors propagate to a boundary that logs them.
- Clean up with with/finally and write helpful messages.
Common mistakes
except: pass
Avoid
Prefer
Silent failure means data loss nobody notices.
Exceptions for normal flow
Avoid
Prefer
A simple, expected case reads better with dict.get.
Important notes
- The logging module's logger.exception() records the message and traceback inside an except block.
Key takeaways
- Specific handlers, no silent failures.
- Prefer EAFP when failure is rare or checks could race.
- Handle errors where you can act; clean up reliably.
Try it yourself
- 1Review a piece of code with a bare except and rewrite it following these practices.
- 2Write a file-reading function using EAFP and another using LBYL; explain which is safer.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhy is a bare except: discouraged?