了解 Python 中异常处理中的控制流

Understanding Control flow in Exception Handling in Python

a=0
try:
    print("In Try Block !")
    a = 10/0
except Exception as e:
    print("In Exception Block !")
    raise e
finally:
    print("In Finally Block !")
    print(a)
    pass

当我运行上面的代码时,我得到如下输出。我不明白这个脚本的流程。

In Try Block !
Traceback (most recent call last):
In Exception Block !
In Finally Block !
0
  File "C:\Users\reccer\Documents\Practicals\test.py", line 7, in <module>
    raise e
  File "C:\Users\reccer\Documents\Practicals\test.py", line 4, in <module>
    a = 10/0
ZeroDivisionError: division by zero
[Finished in 0.3s with exit code 1]
  1. 进入 try 块。
  2. 发现错误
  3. 进入除了块。
  4. 打印“在异常块中!”
  5. 终于进入区块。
  6. 打印 "In Finally Block !" & 打印 a.
  7. 然后执行 从 except 块中筹集 e 的手续。

我无法获得控制流的任何具体参考。

流程正确。 finally 块在离开 try\except\finally 结构之前执行。既然你re-raised异常,异常是被传出结构的,所以finally必须运行先。

a=0
try:
    print("In Try Block !")
    a = 10/0
except Exception as e:
    print("In Exception Block !")
    raise e   # send exception up the call stack, but must run finally first 
finally:
    print("In Finally Block !")
    print(a)
    pass   # not needed

您看到的错误跟踪是由调用您的代码的代码生成的 - 可能是核心 python 引擎。