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")
finally block is always executed after leaving the try statement. In case if some exception was not handled by except block, it is re-raised after execution of finally block.
By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block. Typically, the statements of a finally block run when control leaves a try statement.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
You'll notice that python always returns the last thing to be returned, regardless that the code "reached" return 1 in both functions. A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With