Python Bare except: Why It Hurts and What to Write Instead
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. This guide explains what a bare except really catches, how it differs from except Exception, and the handling patterns that keep failures visible.
What a bare except actually catches
A bare except catches BaseException, the root of the exception hierarchy. That includes KeyboardInterrupt (Ctrl+C), SystemExit (raised by sys.exit), and GeneratorExit — signals that are meant to end a program or generator, not be handled as errors.
The result is scripts that ignore Ctrl+C, workers that will not shut down cleanly, and real bugs (a typo raising NameError, for example) that are silently absorbed.
Before: the catch-everything pattern
def load_settings(path):
try:
with open(path) as f:
return json.load(f)
except:
return {}
After: catch what you expect and log it
import logging
logger = logging.getLogger(__name__)
def load_settings(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
logger.warning("Settings file %s not found, using defaults", path)
return {}
except json.JSONDecodeError:
logger.exception("Settings file %s is not valid JSON", path)
raise
Bare except vs except Exception
except Exception: does not catch KeyboardInterrupt or SystemExit, so it is strictly better than a bare except. It is still broad — it catches programming errors as well as expected failures — so reserve it for top-level boundaries such as a request handler or a worker loop, and always log with logger.exception so the traceback is kept.
except Exception: pass has most of the same problems as a bare except. If you truly need to ignore an error, catch the specific type and leave a comment explaining why.
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
- Prefer contextlib.suppress(SpecificError) when ignoring an error is genuinely intended
Python support in CodeInspector
Python analysis is coming soon to CodeInspector, with checks for bare except clauses, long functions, deeply nested code, hardcoded secrets, and exception handlers without logging. Today you can scan C#, Java, JavaScript, TypeScript, and C++ repositories at https://codeinspector.app — the same exception-handling rules (empty catch blocks, missing logging) apply there.