Python error handling
Skill Amey-Thakur/AI-SKILLS/skills/python/python-error-handling
Design exception hierarchies, catch narrowly, and preserve error context so failures stay diagnosable. Use when structuring errors in a Python library or application, or cleaning up broad except blocks.From its SKILL.md
npx -y skills add Amey-Thakur/AI-SKILLS --skill python-error-handlingAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 4 stars4 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
2.4 KB, 512 tokens by cl100k_base, as published. Nobody here has run it
Python error handling
An exception is part of your API. Callers can only handle what you raise deliberately and document; everything else is a bug report.
Method
- Define one root exception per package.
class AppError(Exception), then a small tree of specific subclasses (ConfigError,RetryableError). Callers catch your root to shield themselves from your internals, or a leaf to handle one case. Never raise bareException. - Catch the narrowest type that you can act on.
except OSErrorwhen you handle missing files; neverexcept Exceptionexcept at a top-level boundary that logs and exits or returns a 500. An unhandled exception with a clean traceback beats a swallowed one every time. - Preserve context when translating. Re-raise with
raise ConfigError("bad port") from excso the original traceback chains.from Noneis only for deliberately hiding an implementation detail, and deserves a comment. - Keep try blocks one line where possible. Wrap only the statement that can fail, not the whole function; a broad block hides which call raised and catches errors you never meant to.
- Put cleanup in finally or a context manager. Resource release must not
depend on success. If you write the same try/finally twice, write a
contextlib.contextmanagerinstead. - Use ExceptionGroup for concurrent failures. On 3.11+, TaskGroup and
your own fan-out code raise groups; handle them with
except*per type rather than flattening to the first error and losing the rest. - Decide retryable vs fatal at raise time. Encode it in the type
(
RetryableError) or an attribute, not by string-matching messages at the call site.
Boundaries
- Exceptions are for exceptional paths. An expected absent value is a
Nonereturn or a sentinel, not a raise; parsing user input that often fails may deserve a result object instead. - Do not log and re-raise at every level; one log at the boundary where the exception is finally handled, or you flood logs with duplicates.
- Never use exceptions for flow control across module boundaries; that is an API contract disguised as an accident.
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.