pythonbottlefinallytry-finally

What does "finally: pass" do in Python? (e.g. in try – except – finally)


I would have assumed a finally clause with only a pass to be pointless.

But in a Bottle template, the following code for an optional include would not work without it.
The result would contain everything before, and the included code itself, but nothing after it.
(See the corresponding question.)

try:
    include(optional_view)
except NameError:
    pass
finally:
    pass

What does finally: pass do, and when is it useful?


Solution

  • finally: pass does nothing, but you don't actually have finally: pass. You're writing a Bottle template, not Python, and you have broken Bottle template syntax.

    Bottle templates ignore indentation in inline code, which means they need a different way to tell when a block statement ends. Bottle templates use a special end keyword for this. Your try-except needs an end:

    try:
        whatever()
    except NameError:
        pass
    end
    

    Otherwise, the except block continues, and stuff that wasn't supposed to go in the except is considered part of the except.

    With finally: pass, the stuff that was incorrectly part of the except is now incorrectly part of the finally, so it runs in cases where it wouldn't have run as part of the except.