flake8-bugbear icon indicating copy to clipboard operation
flake8-bugbear copied to clipboard

Confusing B001 message when catching empty tuple

Open TomFryers opened this issue 3 years ago • 3 comments

This code

    try:
        raise BaseException()
    except ():
        pass

gives this error message

B001 Do not use except ():, it also catches unexpected events like memory errors, interrupts, system exit, and so on. Prefer except Exception:. If you're sure what you're doing, be explicit and write except BaseException:.

However, except (): doesn't catch anything at all! Running the above code raises a BaseException. Perhaps a warning is warranted here, but with a different message.

TomFryers avatar Sep 02 '22 18:09 TomFryers

Yeah, I was not involved when this actual check was added and I agree this does indeed raise BaseException, in Python 2 too (I tested on a Mac of mine):

cooper-mbp:~ cooper$ chmod +x /tmp/be.py
cooper-mbp:~ cooper$ /tmp/be.py
Traceback (most recent call last):
  File "/tmp/be.py", line 4, in <module>
    raise BaseException()
BaseException
#!/usr/bin/env python

try:
    raise BaseException()
except ():
    pass

@ambv - Any memory here of why etc.? - I wanted to make sure it wasn't different in Python 2.

cooperlees avatar Sep 04 '22 23:09 cooperlees

It's a bug in B001 handling. B001 is about except:. It uses the AST to figure out if the except block's exception is "empty". An empty tuple is falsy in Python so it looks "empty". It's good we catch it anyway but I agree with TomFryers that it should yield a different error message, possibly even a different error code.

ambv avatar Sep 06 '22 08:09 ambv

I'd vote for a different error code; instead of catching too much this catches nothing, which is almost surely unintended.

Zac-HD avatar Oct 06 '22 04:10 Zac-HD