rspec/rules/S5708/python/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

80 lines
2.5 KiB
Plaintext

== Why is this an issue?
In Python 3, attempting to catch in an ``++except++`` statement an object which does not derive from BaseException will raise a ``++TypeError++``. In Python 2 it is possible to raise old-style classes but this shouldn't be done anymore in order to be compatible with Python 3.
In order to catch multiple exceptions in an ``++except++`` statement, a tuple of exception classes should be provided.
If you are about to create a custom Exception class, note that custom exceptions should inherit from ``++Exception++``, not ``++BaseException++``. ``++Exception++`` allows people to catch all exceptions except the ones explicitly asking the interpreter to stop, such as ``++KeyboardInterrupt++`` and https://docs.python.org/3/library/exceptions.html#GeneratorExit[``++GeneratorExit++``] which is not an error. See https://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes[PEP 352] for more information.
This rule raises an issue when the expression used in an ``++except++`` statement is not a class deriving from ``++BaseException++`` nor a tuple of such classes.
=== Noncompliant code example
[source,python]
----
class CustomException:
"""An Invalid exception class."""
try:
"a string" * 42
except CustomException: # Noncompliant
print("exception")
except (None, list()): # Noncompliant * 2
print("exception")
try:
"a string" * 42
except [TypeError, ValueError]: # Noncompliant. Lists are not accepted.
print("exception")
except {TypeError, ValueError}: # Noncompliant. Sets are not accepted.
print("exception")
----
=== Compliant solution
[source,python]
----
class MyError(Exception):
pass
try:
"a string" * 42
except (MyError, TypeError):
print("exception")
----
== Resources
* Python documentation - https://docs.python.org/3/tutorial/errors.html[Errors and Exceptions]
* Python documentation - https://docs.python.org/3/reference/compound_stmts.html#except[the ``++try++`` statement]
* https://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes[PEP 352 - Required Superclass for Exceptions]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Change this expression to be a class deriving from BaseException or a tuple of such classes.
=== Highlighting
The expression which does not resolve in a valid exception class or a tuple of such classes.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]