Removing bare except: is sometimes a good idea but not always. Beware about Pycharm's warning on this.
PyCharm is reporting a warning from pycodestyle which cannot enforce the rule correctly so it enforces the rule incorrectly. See issue: E722: (bare excepts) too strict (reraise)
As a general rule:
- bare except for cleanup is the nearly always the right thing to do when
finally: won't do.
- bare except for logging often the right thing to do, but depends on whether you want to see logging of deliberate exit.
In both cases you MUST re-raise with a subsiquent bare raise.
PEP 8 Says:
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).
A good rule of thumb is to limit use of bare ‘except’ clauses to two cases:
- If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
- If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.
General Advice
Always re-raise a bare except
Good:
try:
do_something()
except:
logging.exception("Failed")
raise
Bad
try:
do_something()
except:
logger.exception("Failed")
💥 This just ate a Ctrl-C or SystemExit
Make sure you always clean up
In cases were you need to clean up on error (and only on error), bare except is better
Good
file = open("my_file.txt", "w")
try:
with file:
file.write("something")
except:
os.unlink("my_file.txt")
raise
Bad
file = open("my_file.txt", "w")
try:
with file:
file.write("something")
except Exception:
os.unlink("my_file.txt")
raise
💥 If the user hits CTRL-C at the keyboard at the wrong moment, the file gets left behind.