Overzealous except clause
suggest changeA bare except catches exceptions such as KeyboardInterrupt and SystemExit, can hide programming errors, and often leaves the program in an invalid state:
try:
result = get_result()[0]
except: # Avoid this broad handler.
result = ""
Catch only errors the code can recover from. Keep unrelated operations in separate try statements so the source of a failure remains clear:
try:
results = get_result()
except NetworkError:
logger.exception("Could not retrieve the result")
raise
try:
result = results[0]
except IndexError:
result = ""
logger.info("Got result: %r", result)
logger.exception() records the active traceback. Re-raising with a bare raise preserves that traceback for the caller.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents