[Python] Break statement in finally block swallows exception

Discussão em 'Python' iniciado por Stack, Julho 17, 2025.

  1. Stack

    Stack Membro Participativo

    Consider:

    def raiseMe( text="Test error" ):
    raise Exception( text )

    def break_in_finally_test():
    for i in range(5):
    if i==2:
    try:
    raiseMe()
    except:
    raise
    else:
    print "succeeded!"
    finally:
    print "testing this!"
    break

    if __name__=='__main__':
    break_in_finally_test()


    I expected to see Exception( "Test error" ) to be raised, but instead only "testing this" is printed. The intention, of course, was to call raiseMe() only once, no matter if we succeed or not - but if it raises an exception, I would have wanted to see that!

    Why does break swallow the exception that I explicitly raise?

    Continue reading...

Compartilhe esta Página