Python 简明教程

Python - The try-finally Block

Python Try-Finally Block

在 Python 中,try-finally 块用于确保执行特定代码,无论是否引发异常。与处理异常的 try-except 块不同,try-finally 块主要关注必须发生的清理操作,确保正确释放资源并完成关键任务。

In Python, the try-finally block is used to ensure that certain code executes, regardless of whether an exception is raised or not. Unlike the try-except block, which handles exceptions, the try-finally block focuses on cleanup operations that must occur, ensuring resources are properly released and critical tasks are completed.

Syntax

try-finally 语句的语法如下——

The syntax of the try-finally statement is as follows −

try:
   # Code that might raise exceptions
   risky_code()
finally:
   # Code that always runs, regardless of exceptions
   cleanup_code()

Example

我们考虑一个示例,在其中我们希望以写入模式 ("w") 打开一个文件,向其中写入一些内容,并确保无论使用 finally 块成功还是失败,文件都已关闭——

Let us consider an example where we want to open a file in write mode ("w"), writes some content to it, and ensures the file is closed regardless of success or failure using a finally block −

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()

如果您没有以写模式打开文件的权限,那么它将生成以下 output

If you do not have permission to open the file in writing mode, then it will produce the following output

Error: can't find file or read data

相同的示例可以更简洁地写为如下 −

The same example can be written more cleanly as follows −

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 语句中处理。

When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.

Exception with Arguments

异常可以具有一个参数,它是一个关于问题提供附加信息的值。参数的内容根据异常而有所不同。你通过如下在 except 子句中提供一个变量来捕获异常的参数:

An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception’s argument by supplying a variable in the except clause as follows −

try:
   You do your operations here
   ......................
except ExceptionType as Argument:
   You can print value of Argument here...

如果编写代码来处理单个异常,则可以在 except 语句中让一个变量跟在异常名称后面。如果正在捕捉多个异常,则可以让一个变量跟在异常元组的后面。

If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.

此变量接收异常的值,该值大多包含异常的成因。此变量可以接收单个值,或以元组形式接收多个值。此元组通常包含错误字符串、错误号和错误位置。

This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.

Example

下面是一个处理单个异常的示例:

Following is an example for a single exception −

# 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")

它将生成以下 output

It will produce the following output

The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'