Hello Python developers,
Handling exceptions is always complex whatever the programming language and Python exception system has its own characteristics: else
block, bare raise
statement, difference between BaseException
and Exception
, … and developers can easily fall into a trap.
That’s why the Python analyzer was updated to help you write better code when it comes to raise, catch and manage exceptions.
In total, we added 14 new rules to help you on that field:
Bug Detections:
- S1045: All “except” blocks should be able to catch exceptions (Blocker)
- S5708: Caught Exceptions must derive from BaseException (Blocker)
- S5714: Boolean expressions of exceptions should not be used in “except” statements (Blocker)
- S1143: Break, continue and return statements should not occur in “finally” blocks (Critical)
- S5707: Exceptions’ “__cause__” should be either an Exception or None (Critical)
Code Smell Detections:
- S5709: Custom Exception classes should inherit from “Exception” or one of its subclasses (Critical)
- S5754: “SystemExit” should be re-raised (Critical)
- S5747: Bare “raise” statements should only be used in “except” blocks (Critical)
- S5712: Some special methods should return “NotImplemented” instead of raising “NotImplementedError” (Critical)
- S5727: Comparison to None should not be constant (Critical)
- S112: “Exception” and “BaseException” should not be raised (Major)
- S5704: Bare “raise” statements should not be used in “finally” blocks (Critical)
- S5706: Special method “__exit__” should not re-raise the provided exception (Major)
- S5713: A subclass should not be in the same “except” statement as a parent class (Minor)
For example, on Sentry, S1045 raises an issue about ApiUnauthorized
because it extends ApiError
and ApiError
is already caught a couple of lines before ApiUnauthorized
:
Defintion of ApiUnauthorized
in coreapi.py
These features are already available on SonarCloud, and will be included in SonarQube 8.3. If you can’t wait, you can already install the v2.7 of the Python analyzer from the Marketplace.
Alex