Advertisement
Beginner Python, Exception Handling

Why is a bare 'except:' clause (catching everything with no type specified) generally discouraged?

Short answer

A bare 'except:' catches literally everything, including SystemExit and KeyboardInterrupt (which are meant to actually terminate the program), silently swallowing bugs like typos (NameError) or programming mistakes that should surface loudly rather than being hidden — 'except…

Save Python mock interview
Advertisement
AModel answer
A bare 'except:' catches literally everything, including SystemExit and KeyboardInterrupt (which are meant to actually terminate the program), silently swallowing bugs like typos (NameError) or programming mistakes that should surface loudly rather than being hidden — 'except Exception:' is a safer, still-broad alternative that excludes those system-level exceptions.
# Risky: catches EVERYTHING, including Ctrl+C and typos
try:
    resutl = compute()  # typo -- NameError
except:
    pass  # silently swallows the typo bug, and even Ctrl+C!

# Safer: still broad, but excludes SystemExit/KeyboardInterrupt
try:
    result = compute()
except Exception as e:
    logging.error(f"Unexpected error: {e}")
Real-world example
Debugging a program that couldn't be interrupted with Ctrl+C because a bare except: clause was silently swallowing the KeyboardInterrupt.
Likely follow-ups
  • What specific exception classes does 'except Exception' still fail to catch, that only a bare 'except:' would?
Related topics