7

My code contains a regular try-except block. I downloaded the pycodestyle library to test pep8 on my code. I tested my code and I got the following PEP8 error:

E722 do not use bare 'except'

Why does this happen, and how can I fix it? Thanks.

Mr. Hax
  • 195
  • 1
  • 1
  • 10

1 Answers1

15

You should include a specific exception.

For example,

try:
   <stuff>
except IndexError:
   <stuff>

Instead of

try:
   <stuff>
except:
   <stuff>

It helps with debugging - you'll know if an unexpected error pops up, and the error won't fly by possibly messing something else up.

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
  • 2
    [This StackOverflow answer](https://stackoverflow.com/a/14797508/6947337) goes into more detail as to why specifying exceptions is a good idea. – rlee827 Jun 26 '18 at 03:26
  • 1
    Is it reasonable to ignore this rule if you have a top level try-except to make sure unexpected errors are redirected to a logger and/or a remote monitoring service? – Johan Falkenjack Jun 11 '20 at 13:13
  • 1
    In that case you could use `except Exception as e:` so you know what the error is – whackamadoodle3000 Jun 11 '20 at 18:37