Warning on the catching of all exception types
Affects | Status | Importance | Assigned to | Milestone | |
---|---|---|---|---|---|
Pyflakes |
Won't Fix
|
Undecided
|
Unassigned |
Bug Description
It's generally bad practice to catch all exception types like this:
try:
o = open('file.txt', 'rb')
data = json.loads(
except:
print("Can't parse file")
For example, sometimes the `except` block handles the wrong sort of exception. There are many sorts of exceptions that could have been thrown in the example above (file not found, bad json format, etc), and the original exception would have done a much better job of informing us of what went wrong. The author should only catch specific types of exceptions for specific ways to handle them.
It would be great if a rule could be added to catch instances where all exceptions are being handled, either in the above form or with the catch-all `except Exception:`. Where an explicit catch-all could be silenced with a `# NOQA` in instances where they really want everything caught.
Sadly there are a lot of false positives here, and pyflakes tries to avoid all false positives. While one class of false positives can be ignored easily (if there is a 'raise' call in the except block), not all have that form. It's a bit of a style issue. For those cases where you really do want to catch all exceptions, it "really" better to write "except:" instead of "except BaseException:"? And do you "really" want to be catching BaseException instead of Exception? Usually you don't, but not always.
"except Exception:", the less bad variant, is very common in acceptable forms (i.e., false positives for a rule that disallows them).