Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersSeniorOccasionalTroubleshooting

What happens if both a `try` block and its `finally` block contain a `return` statement?

Answer

The `return` (or `break`/`continue`) in the `finally` block always wins: it silently discards the `try` block's return value entirely, and it also silently swallows any exception that was propagating out of the `try`/`except` blocks, because control flow leaving via `finally` overrides whatever was leaving the `try` section. This is almost always an accidental bug rather than an intentional design choice, which is why linters typically flag a `return` inside `finally`, and Python 3.14 added its own compiler `SyntaxWarning` for a `return`, `break` or `continue` inside a `finally` block for exactly this reason — the pattern remains legal syntax, but the interpreter itself now calls it out.

Strong answer includes

  • return in finally always wins, discarding the try block's return value
  • it also silently swallows any propagating exception
  • Python 3.14 added a compiler SyntaxWarning for return/break/continue inside finally

Practical example

Python example
def f():
    try:
        return 1
    finally:
        return 2

returns 2, and

Python example
def g():
    try:
        raise ValueError()
    finally:
        return 3

returns 3 and completely swallows the ValueError.

#exceptions#gotchas#control-flow

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics