Python中的finally关键字

在任何编程语言中,我们都会发现引发异常的情况。Python具有许多内置的异常处理机制。此异常名称处理了一些错误。Python也有一个名为finally的块,无论是否处理异常,该块都将执行。

语法

try:
   # main python Code....
except:
   # It is optional block
   # Code to handle exception
finally:
   # This Code that is always executed

示例

在下面的代码中,我们看到一个名为NameError的异常。在这里,我们创建一个引用未声明变量的代码。即使处理了异常,代码仍然会运行到“最终”块中。“ finally”块中的代码也将执行。

try:
   var1 = 'Tutorials'
   # NameError is raised
   print(var2)

# Handle the exception
except NameError:
   print("在本地或全局范围内找不到变量。")
finally:
   # Regardless of exception generation,
   # this block is always executed
   print('finally block code here')

输出结果

运行上面的代码给我们以下结果-

在本地或全局范围内找不到变量。
finally block code here

无异常处理

假设我们设计的代码不处理异常。即使这样,finally块仍将执行未处理异常的代码。

例子

try:
   var1 = 'Tutorials'
   # NameError is raised
   print(var2)
# No exception handling
finally:
   # Regardless of exception generation,
   # this block is always executed
   print('finally block code here')

输出结果

运行上面的代码给我们以下结果-

finally block code here
Traceback (most recent call last):
   File "xxx.py", line 4, in
      print(var2)
NameError: name 'var2' is not defined