Warning on the catching of all exception types

Bug #1628263 reported by Conrad Dean
8
This bug affects 1 person
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(o.read())
   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.

Revision history for this message
asmeurer (asmeurer) wrote :

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

Revision history for this message
Phil Frost (bitglue) wrote :
Changed in pyflakes:
status: New → Won't Fix
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.