📜  在Python中定义清理操作

📅  最后修改于: 2022-05-13 01:54:50.460000             🧑  作者: Mango

在Python中定义清理操作

想一想您总是希望程序执行的任务,无论它运行完美还是引发任何类型的错误。例如,我们使用带有可选子句“finally”try语句来执行清理操作,该操作必须在所有条件下执行。
清理动作:在离开try语句之前, “finally”子句总是被执行,无论是否引发异常。这些条款旨在定义在所有情况下都必须执行的清理操作。
每当发生异常并且未由except子句处理时,首先会发生finally ,然后将错误作为默认值引发 [代码 3]。

说明“定义清理操作”的Python程序

代码1:代码正常工作,最后采取清理措施

# Python code to illustrate
# clean up actions
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
    else:
        print("Yeah ! Your answer is:", result)
    finally:
        print("I'm finally clause, always raised !! ")
  
# Look at parameters and note the working of Program
divide(3, 2)

输出 :

Yeah ! Your answer is : 1
I'm finally clause, always raised !! 


代码 2:代码引发错误,并在except子句中小心处理。请注意,最后会执行清理操作。

# Python code to illustrate
# clean up actions
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
    else:
        print("Yeah ! Your answer is:", result)
    finally:
        print("I'm finally clause, always raised !! ")
  
# Look at parameters and note the working of Program
divide(3, 0)

输出 :

Sorry ! You are dividing by zero 
I'm finally clause, always raised !!

代码 3:代码,引发错误,但我们没有任何except子句来处理它。因此,首先采取清理操作,然后编译器会引发错误(默认情况下)

# Python code to illustrate
# clean up actions
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
    else:
        print("Yeah ! Your answer is:", result)
    finally:
        print("I'm finally clause, always raised !! ")
  
# Look at parameters and note the working of Program
divide(3, "3")

输出 :

I'm finally clause, always raised !! 

错误:

Traceback (most recent call last):
  File "C:/Users/DELL/Desktop/Code.py", line 15, in 
    divide(3, "3")
  File "C:/Users/DELL/Desktop/Code.py", line 7, in divide
    result = x // y
TypeError: unsupported operand type(s) for //: 'int' and 'str'