org.sonar.l10n.py.rules.python.S5713.html Maven / Gradle / Ivy
This rule raises an issue when an exception class is duplicated in an except
statement, or when an exception class has a parent class
in the same except
statement.
Why is this an issue?
In Python it is possible to catch multiple types of exception in a single except
statement using a tuple of the exceptions.
Repeating an exception class in a single except
statement will not fail but it does not have any effect. Either the exception class is
not the one which should be caught, or it is duplicated code which should be removed.
Having a subclass and a parent class in the same except
statement does not provide any benefit either. It is enough to keep only the
parent class.
Code examples
Noncompliant code example
try:
...
except (TypeError, TypeError): # Noncompliant: duplicated code or incorrect exception class.
print("Foo")
try:
...
except (NotImplementedError, RuntimeError): # Noncompliant: NotImplementedError inherits from RuntimeError.
print("Foo")
Compliant solution
try:
...
except (TypeError, ValueError):
print("Foo")
try:
...
except RuntimeError:
print("Foo")
Resources
Documentation
- Python Documentation - Handling Exceptions
- Python Documentation - Exception hierarchy
© 2015 - 2024 Weber Informatics LLC | Privacy Policy