github / codeql

CodeQL: the libraries and queries that power security researchers around the world, as well as code scanning in GitHub Advanced Security
https://codeql.github.com
MIT License
7.67k stars 1.54k forks source link

LGTM.com - false positive - Python - except (Exception if condition else NeverRaise) #3280

Open jbarlow83 opened 4 years ago

jbarlow83 commented 4 years ago

Description of the false positive

This is both a valid construct and a compact way to express the fact that under certain conditions, a particular except block should not be processed.

https://lgtm.com/projects/g/jbarlow83/OCRmyPDF/snapshot/c3799e9226e368d3339d8c411484892ba54cbd81/files/src/ocrmypdf/_sync.py?sort=name&dir=ASC&mode=heatmap#x17505d1e5cd98f90:1

RasmusWL commented 4 years ago

It seems like a real alert to me. In the case where not api is false, the second and third except blocks will be unreachable, since all three except block will only catch exceptions of type NeverRaise.

You might argue that it's not a very useful alert, which I guess ends up being a matter of viewpoint/taste.

One way to get around this would be to structure your code as

# if api, we want to raise the exception; otherwise we will perform special handling
except (BaseException if api else NeverRaise):
    raise
except KeyboardInterrupt as e:
    ...
except ExitCodeException as e:
    ...
except Exception as e:
    ...