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热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短