Python: try、except、else、finally 执行顺序

目录

一、触发了异常时的顺序

1.1 异常演示代码

1.2 异常代码执行顺序

二、未触发异常时的顺序

2.1 无异常演示代码

2.2 无异常代码执行顺序

三、流程被 return 结束的情况

3.1 被 return 结束的代码

3.2 被 return 结束代码的执行顺序


一、触发了异常时的顺序

1.1 异常演示代码

def exception_happen():
    try:
        print("step 1")
        raise Exception("step 2")
    except Exception as e:
        print("step 3")
        raise Exception("step 5")
    else:
        print("not exec here")
    finally:
        print("step 4")

if "__main__" == __name__:
    exception_happen()

1.2 异常代码执行顺序

step 1
step 3
step 4
Traceback (most recent call last):
  File "finally.py", line 7, in exception_happen
    raise Exception("step 2")
Exception: step 2

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "finally.py", line 29, in <module>
    exception_happen()
  File "finally.py", line 10, in exception_happen
    raise Exception("step 5")
Exception: step 5

二、未触发异常时的顺序

2.1 无异常演示代码

def no_exception_happen():
    try:
        print("step 1")
    except Exception as e:
        print("not exec here")
        raise e
    else:
        print("step 2")
    finally:
        print("step 3")


if "__main__" == __name__:
    no_exception_happen()

2.2 无异常代码执行顺序

step 1
step 2
step 3

三、流程被 return 结束的情况

3.1 被 return 结束的代码

def with_return():
    try:
        print("step 1")
        return 1
    except Exception as e:
        print("not exec here")
        raise e
    else:
        print("step 2")
    finally:
        print("step 3")

    return 2


if "__main__" == __name__:
    print("return ", with_return())

3.2 被 return 结束代码的执行顺序

step 1
step 3
return  1

 


版权声明:本文为fengbohello原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。