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!
1 Answer
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.
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.
Yeah, you’re right! Returning from a finally block can lead to confusing behavior. It’s usually best to avoid that.