Python try-finally 块
在 Python 中,try-finally 块用于确保某些代码执行,无论是否引发异常。与处理异常的 try-except 块不同,try-finally 块侧重于必须发生的清理操作,确保正确释放资源并完成关键任务。
语法
try-finally 语句的语法如下 -
try:
# Code that might raise exceptions
risky_code()
finally:
# Code that always runs, regardless of exceptions
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 语句中让变量跟在异常名称后面。如果要捕获多个异常,则可以让变量跟随异常的元组。
此变量接收异常的值,主要包含异常的原因。该变量可以接收单个值或元组形式的多个值。此 Tuples 通常包含错误字符串、错误号和错误位置。
例以下是单个异常的示例 -
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError as Argument:
print("The argument does not contain numbers\n",Argument)
# Call above function here.
temp_convert("xyz")
它将产生以下输出 -
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
invalid literal for int() with base 10: 'xyz'