易百教程

65、如何在 Python 中使用 Try/Except/Finally 处理异常?

Python 制定了 Try、Except、Finally 构造来处理错误和异常。 我们将缩进的不安全代码附在 try 块下。 可以将后备代码保留在 except 块中。任何打算最后执行的指令都应该在 finally 块下。

try:
    print("Executing code in the try block")
    print(exception)
except:
    print("Entering in the except block")
finally:
    print("Reached to the final block")

运行结果:

Executing code in the try block
Entering in the except block
Reached to the final block