rspec/rules/S5704/python/rule.adoc

94 lines
2.3 KiB
Plaintext
Raw Normal View History

2023-08-03 11:01:28 +02:00
This rule raises an issue when a bare ``++raise++`` statements is in a ``++finally++`` block.
== Why is this an issue?
2021-04-28 16:49:39 +02:00
A bare ``++raise++`` statement, i.e. a ``++raise++`` with no exception provided, will re-raise the last active exception in the current scope. If no exception is active a ``++RuntimeError++`` is raised instead.
If the bare "raise" statement is in a ``++finally++`` block, it will only have an active exception to re-raise when an exception from the ``++try++`` block is not caught or when an exception is raised by an ``++except++`` or ``++else++`` block. Thus bare ``++raise++`` statements should not be relied upon in ``++finally++`` blocks. It is simpler to let the exception raise automatically.
2023-08-03 11:01:28 +02:00
=== Code examples
2023-08-03 11:01:28 +02:00
==== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-08-03 11:01:28 +02:00
[source,python,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
def foo(param):
result = 0
try:
print("foo")
except ValueError as e:
pass
else:
if param:
raise ValueError()
finally:
if param:
2023-08-03 11:01:28 +02:00
raise # Noncompliant: This will fail in some context.
2021-04-28 16:49:39 +02:00
else:
result = 1
return result
----
2023-08-03 11:01:28 +02:00
==== Compliant solution
2021-04-28 16:49:39 +02:00
2023-08-03 11:01:28 +02:00
[source,python,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
def foo(param):
result = 0
try:
print("foo")
except ValueError as e:
pass
else:
if param:
raise ValueError()
finally:
if not param:
result = 1
return result
----
== Resources
2021-04-28 16:49:39 +02:00
2023-08-03 11:01:28 +02:00
=== Documentation
2021-04-28 16:49:39 +02:00
* Python Documentation - https://docs.python.org/3/reference/simple_stmts.html#raise[The ``++raise++`` statement]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Refactor this code so that any active exception raises naturally
=== Highlighting
Primary:
* The bare "raise" statement
Secondary:
* the parent "finally:" statement
'''
== Comments And Links
(visible only on this page)
=== is related to: S5747
=== on 29 Jan 2020, 13:56:33 Nicolas Harraudeau wrote:
This rule is similar to RSPEC-1163 but the problem is a little different. It is perfectly ok to raise an exception in a ``++finally++`` block in python. Python will automatically link the new exception to any exception raised in the ``++try++`` block. However a bare ``++raise++`` is problematic as it can fail.
endif::env-github,rspecator-view[]