Python 9.3.6 Advanced Road abnormal captured in the finally clause

Disclaimer: This tutorial learning exchanges only, not for commercial use. https://blog.csdn.net/weixin_45086637/article/details/91050059

Abnormal captured in the finally clause 9.3.6

The last statement of catch exceptions clause is finally. From the name clause basically you can determine what to do with. All need to be finally ending code into finally clause. Whether normal execution, or an exception is thrown, the last clause of the code will be executed finally, it should close in the finally clause placing code resource, such as closing a file, close the database and so on.

If you use the return statement to exit the function, then the first execution of the code itself finally, will exit the function. So do not worry about itself finally in the code will not be executed, just add the finally clause try statements, and program execution flow into the try statement, finally the code itself will be performed.

try:
    ...
except:
    ...
finally:	# 无论是否抛出异常,都会执行finally子句中的代码
    ...

[Example 9.7] This example demonstrates the performance finally clause in various scenarios.

# 未抛出异常时执行finally子句中的代码

def fun1():
    try:
        print('fun1 正常执行')
    finally:
        print('fun1 finally')

# 抛出异常时执行finally子句中的代码

def fun2():
    try:
        raise Exception
    except:
        print('fun2 抛出异常')
    finally:
        print('fun2 finally')

# 用return语句退出函数之前执行finally子句中的代码

def fun3():
    try:
        return 20
    finally:
        print('fun3 finally')

# 抛出异常时执行finally子句中的代码,但在finally子句中执行del x操作,再一次抛出了异常

def fun4():
    try:
        x = 1/0
    except ZeroDivisionError as e:
        print(e)
    finally:
        print('fun4 finally')
        del x

fun1()
fun2()
print(fun3())
fun4()

Output:

fun1 正常执行
fun1 finally
fun2 抛出异常
fun2 finally
fun3 finally
20
division by zero
fun4 finally
Traceback (most recent call last):
  File "/Users/limingda/PycharmProjects/untitled6/test3.py", line 41, in <module>
    fun4()
  File "/Users/limingda/PycharmProjects/untitled6/test3.py", line 36, in fun4
    del x
UnboundLocalError: local variable 'x' referenced before assignment

We can see from the above code, when the function exits through the return statement in fun3 function, will first execute the code itself finally in, and then exit. In fun4 function, although finally clause of the code normal execution, but try to delete the statement del x variables in the finally clause, but since the beginning of creation due to the variable x thrown (the denominator is 0), not Creating successful, so the x variable does not actually exist, and therefore, when using the del statement to delete a variable that does not exist will throw an exception, but this is an exception is thrown in the finally clause, and no other statements try to capture this exception, the exception will directly lead to a crash. Therefore, in the finally clause, should be avoided as much as possible to perform easily throw the exception, if you must perform this kind of statement, it suggested adding a try statement again.

def fun4():
    try:
        x = 1/0
    except ZeroDivisionError as e:
        print(e)
    finally:
        print('fun4 finally')
        try:
            del x
        except Exception as e:
            print(e)

Output:

local variable 'x' referenced before assignment

Guess you like

Origin blog.csdn.net/weixin_45086637/article/details/91050059