Python Bare except: Why It Hurts and What to Write Instead (video)

A bare except in Python catches everything, including KeyboardInterrupt and SystemExit. Learn why that hides bugs, how it differs from except Exception, and the patterns to use instead.

Read the full article

Transcript

Python Bare except: Why It Hurts and What to Write Instead. Here's the short version.

A bare except is an except clause with no exception type: just except: on its own line. It looks like defensive coding, but it catches every exception Python can raise — including the ones that are supposed to stop your program.

What a bare except actually catches. A bare except catches BaseException, the root of the exception hierarchy. The result is scripts that ignore Ctrl+C, workers that will not shut down cleanly, and real bugs that are silently absorbed.

Here's an example: Every failure — and Ctrl+C — disappears.

Bare except vs except Exception. except Exception: does not catch KeyboardInterrupt or SystemExit, so it is strictly better than a bare except. except Exception: pass has most of the same problems as a bare except.

Python exception handling checklist. Catch the narrowest exception type that makes sense. Log handled exceptions with context; use logger.exception inside except blocks to keep the traceback. Re-raise when the function cannot actually recover. Use except Exception only at top-level boundaries, never bare except.

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos