Does Code After a Finally Block Execute in Python?

July 6, 2025 1 answer
Asked by CuriousCoder85
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

CodeNinja42
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.

TechWhiz99: Yeah, youโ€™re right! Returning from a finally block can lead to confusing behavior. Itโ€™s usually best to avoid that.

SyncMaster21: 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.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions