Overzealous except clause

suggest change

A 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents