📜  Python中的 Try、Except、else 和 finally

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

Python中的 Try、Except、else 和 finally

异常是在程序执行期间发生的事件。它也称为运行时错误。当该错误发生时, Python会在执行过程中生成一个可以处理的异常,从而避免您的程序中断。

例子:

Python3
a = 5
b = 0
print(a/b)


Python3
# Python code to illustrate
# working of try() 
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional
        # Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
   
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)


Python3
# Python code to illustrate
# working of try() 
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)
   
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)


Python3
# Python code to illustrate
# working of try() 
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: 
        # this block is always executed  
        # regardless of exception generation. 
        print('This is always executed')  
 
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)


输出:

Traceback (most recent call last):
  File "/home/8a10be6ca075391a8b174e0987a3e7f5.py", line 3, in 
    print(a/b)
ZeroDivisionError: division by zero

在此代码中,系统无法将数字除以零,因此引发异常。

使用 try、except、else 和 finally 处理异常

  • Try :此块将测试发生的异常错误
  • 除了:在这里您可以处理错误
  • Else :如果没有异常,则将执行此块
  • finally :无论是否生成异常,Finally 块总是被执行

句法:

try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

else:
       # execute if no exception

finally:
      # Some code .....(always executed)

让我们首先了解 try 和 except 是如何工作的——

  • 执行第一个try子句,即tryexcept子句之间的代码。
  • 如果没有异常,那么只有try子句会运行, except子句不会被执行。
  • 如果发生任何异常,将跳过try子句并运行except子句。
  • 如果发生任何异常,但代码中的except子句不处理它,则将其传递给外部try语句。如果异常未处理,则执行停止。
  • 一条try语句可以有多个except子句。

示例:让我们尝试接受用户整数输入并在 except 块中抛出异常。

Python3

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

输出:

Yeah ! Your answer is : 1
Sorry ! You are dividing by zero 

其他条款

只有当 try 子句没有引发异常时,代码才会进入 else 块。

示例:只有在没有异常发生时才会执行 Else 块。

Python3

# Python code to illustrate
# working of try() 
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)
   
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)

输出:

Yeah ! Your answer is : 1
Sorry ! You are dividing by zero

最后关键字

Python提供了一个关键字 finally,它总是在 try 和 except 块之后执行。 finally 块总是在 try 块正常终止后或 try 块由于某些异常终止后执行。

示例:让我们尝试在 except 块中抛出异常,最终将执行任一异常是否会生成

Python3

# Python code to illustrate
# working of try() 
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: 
        # this block is always executed  
        # regardless of exception generation. 
        print('This is always executed')  
 
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)

输出:

Yeah ! Your answer is : 1
This is always executed
Sorry ! You are dividing by zero 
This is always executed