Why is a bare "except:" considered bad practice in Python?
A bare except catches everything, including KeyboardInterrupt and SystemExit, so Ctrl+C stops working and real bugs get hidden. Catch specific exceptions, or at most "except Exception", and log or re-raise what you cannot handle.
Explain it simply
A bare except: is like a smoke alarm that you cover with a towel because it beeps too often. The beeping stops, and so does your warning when there is a real fire.
All exceptions inherit from BaseException. Exception is its child for ordinary errors, while KeyboardInterrupt and SystemExit sit beside it so that they are not caught by accident.
Example
def read_marks(text):
try:
return int(text)
except ValueError:
return 0
print(read_marks("85")) # Output: 85
print(read_marks("abc")) # Output: 0
print(issubclass(KeyboardInterrupt, Exception)) # Output: False
print(issubclass(KeyError, Exception)) # Output: True
print(issubclass(Exception, BaseException)) # Output: TrueHere only ValueError is handled. A typo like inta(text) would still raise NameError and be visible, whereas a bare except would hide it behind a silent 0.
What to say in the interview
"Bare except swallows every exception, including KeyboardInterrupt and SystemExit, and masks bugs like typos. I catch the narrowest exception I can handle. If I must catch broadly, I use except Exception, log it with traceback, and re-raise if I can't recover."
Common mistakes
- Writing
except Exception: pass, which silently ignores errors and makes debugging painful.