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" 块。此外,"finally" 块中的代码也会得到执行。
try:
var1 = 'Tutorials'
# NameError is raised
print(var2)
# Handle the exception
except NameError:
print("variable is not found in local or global scope.")
finally:
# Regardless of exception generation,
# this block is always executed
print('finally block code here')输出
运行以上代码可得到以下结果:−
variable is not found in local or global scope. 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP