
Catch except Exception as exc: (and never a bare except: or except BaseException:) so standard runtime errors are caught and logged without swallowing system-level control signals like KeyboardInterrupt (Ctrl+C), SystemExit (sys.exit()), or GeneratorExit.
Basic Example
import logging
logger = logging.getLogger(__name__)
def run_task(payload: dict) -> str | None:
try:
# 1. Code that might raise an operational/runtime error
value = int(payload["count"])
return f"Processed {100 / value:.2f}"
except (KeyError, ValueError, ZeroDivisionError) as exc:
# 2. Recommended: Catch expected, recoverable errors specifically first
logger.warning("Invalid payload (%s): %s", type(exc).__name__, exc)
return None
except Exception as exc:
# 3. Safe catch-all for all remaining application errors:
# - Logs the full stack trace via `logger.exception(...)`
# - Allows KeyboardInterrupt & SystemExit to propagate normally!
logger.exception("Unexpected failure while running task: %s", exc)
return None
Key Details & Edge Cases
- Why you must NEVER write a bare
except:orexcept BaseException::- In Python’s exception hierarchy,
BaseExceptionis the root class aboveKeyboardInterrupt,SystemExit, andGeneratorExit, whereasExceptionis the base class for all regular program errors (ValueError,TypeError,OSError,RuntimeError, etc.). - A bare
except:(which is equivalent toexcept BaseException:) catchesCtrl+C(KeyboardInterrupt) andsys.exit()(SystemExit), trapping users in unkillable loops and preventing clean process shutdown. Always writeexcept Exception as exc:.
- In Python’s exception hierarchy,
- Never silence exceptions with
except Exception: pass:- Silently ignoring an exception (
pass) hides bugs, corrupts downstream state, and makes debugging nearly impossible. Always log the full traceback usinglogging.exception("...")(ortraceback.print_exc())—or re-raise with a bareraiseafter cleanup if the caller must know the operation failed.
- Silently ignoring an exception (
- Do not capture
asyncio.CancelledErroraccidentally (Python 3.8+):- Since Python 3.8,
asyncio.CancelledErrorinherits directly fromBaseException(notException), soexcept Exception:safely lets task cancellation propagate—unless you manually catchBaseExceptionorCancelledErrorwithout re-raising it.
- Since Python 3.8,
- Use
else:andfinally:to keep thetry:block minimal:- Place only the line(s) that can actually raise the target exception inside
try:, put code that should run only iftry:succeeded insideelse:(so exceptions in follow-up logic aren’t misattributed), and put guaranteed resource cleanup insidefinally:(or use awithcontext manager).
- Place only the line(s) that can actually raise the target exception inside
- Python 3.11+
except*(ExceptionGroup) for concurrent tasks (asyncio.TaskGroup):- When multiple concurrent tasks fail simultaneously inside an
asyncio.TaskGroup, Python raises anExceptionGroup. Useexcept* Exception as eg:when handling grouped concurrent failures.
- When multiple concurrent tasks fail simultaneously inside an
Comparison of Catch-All Exception Patterns in Python
| Pattern | Catches Runtime Errors (ValueError, OSError, etc.)? |
Lets Ctrl+C (KeyboardInterrupt) & sys.exit() Work? |
Preserves Traceback / Diagnostics? | Best Used When |
|---|---|---|---|---|
except (SpecificError, ...) as exc: (Best Practice) |
Only the listed recoverable exceptions | Yes | Yes (when logged or re-raised) | Normal application logic where you know which failures are recoverable. |
except Exception as exc: + logger.exception(...) (Safe Catch-All) |
Yes (all standard runtime errors) | Yes (BaseException control signals pass through) |
Yes (logger.exception records full stack trace) |
Top-level worker loops, request handlers, plugin runners, and batch jobs that must stay alive on unexpected errors. |
except Exception: + raise (after cleanup) |
Yes | Yes | Yes (bare raise preserves original stack trace) |
Rolling back a database transaction or closing a resource before letting the error bubble up. |
Bare except: or except BaseException: (Anti-Pattern) |
Yes | No (swallows Ctrl+C and sys.exit()) |
No (if paired with pass) |
Almost never—avoid in application code. |
You must log in or register to comment.
