rspec/rules/S5704/rule.adoc
2020-06-30 17:16:12 +02:00

52 lines
1.5 KiB
Plaintext

A bare <code>raise</code> statement, i.e. a <code>raise</code> with no exception provided, will re-raise the last active exception in the current scope. If no exception is active a <code>RuntimeError</code> is raised instead.
If the bare "raise" statement is in a <code>finally</code> block, it will only have an active exception to re-raise when an exception from the <code>try</code> block is not caught or when an exception is raised by an <code>except</code> or <code>else</code> block. Thus bare <code>raise</code> statements should not be relied upon in <code>finally</code> blocks. It is simpler to let the exception raise automatically.
This rule raises an issue when a bare <code>raise</code> statements is in a <code>finally</code> block.
== Noncompliant Code Example
----
def foo(param):
result = 0
try:
print("foo")
except ValueError as e:
pass
else:
if param:
raise ValueError()
finally:
if param:
raise # Noncompliant. This will fail in some context.
else:
result = 1
return result
----
== Compliant Solution
----
def foo(param):
result = 0
try:
print("foo")
except ValueError as e:
pass
else:
if param:
raise ValueError()
finally:
if not param:
result = 1
# the exception will raise automatically
return result
----
== See
* Python Documentation - https://docs.python.org/3/reference/simple_stmts.html#raise[The <code>raise</code> statement]