Python - try-finally 块
Python try-finally 块
在 Python 中,try-finally 块用于确保某些代码无论是否发生异常都会执行。与处理异常的 try-except 块不同,try-finally 块专注于必须执行的清理操作,确保资源得到正确释放以及关键任务得到完成。
语法
try-finally 语句的语法如下 −
try: # 可能引发异常的代码 risky_code() finally: # 无论是否发生异常都会执行的代码 cleanup_code()
在 Python 中,使用 try 块进行异常处理时,您可以选择包含 except 子句来捕获特定异常,或者包含 finally 子句来确保某些清理操作得到执行,但不能同时包含两者。
示例
让我们考虑一个示例,我们希望以写模式 ("w") 打开一个文件,向其中写入一些内容,并使用 finally 块确保无论成功或失败文件都会被关闭 −
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
如果您没有权限以写模式打开文件,则会产生以下输出 −
Error: can't find file or read data
同一个示例可以更简洁地编写如下 −
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can\'t find file or read data")
当 try 块中抛出异常时,执行会立即传递到finally 块。在finally 块中的所有语句执行完毕后,异常会被重新抛出,并在 try-except 语句的下一更高层中由 except 语句处理(如果存在)。
带参数的异常
异常可以带有参数,该参数是一个提供有关问题额外信息的数值。参数的内容因异常而异。您可以通过在 except 子句中提供一个变量来捕获异常的参数,如下所示 −
try: You do your operations here ...................... except ExceptionType as Argument: You can print value of Argument here...
如果您编写代码来处理单个异常,可以在 except 语句中让变量跟在异常名称后面。如果您捕获多个异常,可以让变量跟在异常的元组后面。
这个变量接收异常的值,通常包含异常的原因。该变量可以接收单个值或以元组形式的多值。这个元组通常包含错误字符串、错误编号和错误位置。
示例
以下是一个单个异常的示例 −
# 在此处定义一个函数。
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The argument does not contain numbers\n",Argument)
# 在此处调用上述函数。
temp_convert("xyz")
它会产生以下输出 −
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'