64 lines
1.7 KiB
Plaintext
64 lines
1.7 KiB
Plaintext
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
|
|
|
|
[source,python,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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
|
|
|
|
[source,python,diff-id=1,diff-type=compliant]
|
|
----
|
|
try:
|
|
...
|
|
except (TypeError, ValueError):
|
|
print("Foo")
|
|
|
|
try:
|
|
...
|
|
except RuntimeError:
|
|
print("Foo")
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Python Documentation - https://docs.python.org/3/tutorial/errors.html#handling-exceptions[Handling Exceptions]
|
|
* Python Documentation - https://docs.python.org/3/library/exceptions.html#exception-hierarchy[Exception hierarchy]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
include::../highlighting.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|