Pitfalls in try..except...finally that most people don't know about!!

Exception missing:

Please take a look at the code below:

def fun():
    try:
        print('try--start')
        a = 1/0
    except ValueError as ret:
        print (ret)
    finally:
        return 'finally'


print(fun())

Result of execution:

try--start
finally

It stands to reason that a = 1/0 should throw a ZeroDivisionError exception, but there is no exception in the execution result. Let's analyze the reasons for this situation.

When an exception occurs in the try, the except will be executed first, and the interpreter will see if there is a corresponding exception statement after the except. If there is a corresponding exception statement, it will be processed. statement, but if a new exception is generated in finally or a return or break statement is executed, the temporarily saved exception will be lost, resulting in ZeroDivisionError not really being thrown.

return lost in try

Please see the following code:

def fun():
    try:
        print('try--start')
        return 'try return'
    except:
        pass
    finally:
        return 'finally'


print(fun())

The result of the execution is

try--start
finally

Why didn't try return return? Let's analyze the reasons

Finally has a feature, that is, no matter what, the code in finally will be executed, then when the return in try is executed, the function fun will be ended and returned. At this time, due to the characteristics of finally, the return 'try return' in try After being temporarily suspended, when the statement in finally is executed, it returns to execution, but another return is executed in finally, which causes the function to end directly. At this time, the finally in try is lost.

All in our actual development, we should try to avoid using the return statement to return in finally.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325707794&siteId=291194637