Using "try"+"finally" without "except" never generates any error [duplicate]
Asked Answered
E

1

22

I thought that if I use "try" and just "finally" else, without any "except", if the "try" statements couldn't be executed, the "finally" statements should be executed, but after that, an error should be shown in the execution, but in this simple code, where purposely I force an invalid operation, errors never jump. Why?

def division_peligrosa(a, b):
    try:
        a = float(a); b = float(b)
        return a/b
    finally:
        return "Aquí va haber un error..."

print (division_peligrosa(5,0))
print (division_peligrosa("dividendo",28.3))

print ("\nFin del programa, ¡pero nada ocurre!\n")
Elastomer answered 17/4, 2020 at 4:51 Comment(0)
C
40

You can find documented in the section about the try statement:

If the finally clause executes a return, break or continue statement, the saved exception is discarded.

Of course, the fact that it's a documented behavior does not entirely explain the reasoning, so I offer this: a function can only exit in one of two ways, by returning a value or raising an exception. It can not do both.

Since the finally block is commonly used as a cleanup handler, it makes sense for the return to take priority here. You do have the chance to re-raise any exceptions within finally, simply by not using a return statement.

Chilopod answered 17/4, 2020 at 5:37 Comment(1)
This is a good answer, I just want to make it explicit that this behavior is unrelated to the missing except clause. In the OP's example, if you add except: raise the behavior is the sameCarlo

© 2022 - 2024 — McMap. All rights reserved.