Does Code After a Finally Block Execute in Python?
Asked by
underhand-serve
I'm working on a Python method that has some code below a finally block, and I'm curious if that code actually gets executed. My IDE (PyCharm) is giving me a warning that says "This code is unreachable" at the line where I have a return statement. I'm wondering if this warning is correct or if it's a mistake. Here's the method I'm referring to:
def sync(source_path, destination_path, exclusions, processes):
...
try:
...
except (RetryError, IOError, OSError, BaseException) as exception:
...
finally:
...
return comparison
Thanks for any insights!
Answers
It really depends on what the code is hiding under those `...` sections. In a case like the example Iโll share below, the return in the finally block would definitely be unreachable:
```python
def divide(x, y):
try:
result = int(x) / int(y)
except ValueError:
pass
finally:
return x # This ends the function!
return result # unreachable!
```
In some cases, if you need code to run only if there are no exceptions, you'd want to look into using a tryโelse construct instead. But generally, it might be good to first analyze the flow in your finally section.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_clover_patch: Yeah, youโre right! Returning from a finally block can lead to confusing behavior. Itโs usually best to avoid that.
harpsichord tuning: Thanks for the clarification! Just to add, in my specific case the statement in the finally block is just logging information, so it doesn't affect control flow.