📜  Python尝试除外

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

Python尝试除外

Python中的错误可以有两种类型,即语法错误和异常。错误是程序中的问题,由于该问题程序将停止执行。另一方面,当一些内部事件发生改变程序的正常流程时,就会引发异常。
注意:有关详细信息,请参阅Python中的错误和异常
一些常见的异常错误是:

  • IOError:如果文件无法打开
  • KeyboardInterrupt:当用户按下不需要的键时
  • ValueError:当内置函数接收到错误的参数时
  • EOFError:如果在未读取任何数据的情况下命中文件结束
  • ImportError:如果找不到模块

在Python中尝试例外

Try 和 except 语句用于在我们的Python代码中处理这些错误。 try 块用于检查某些代码是否有错误,即当程序没有错误时,try 块内的代码将执行。而只要程序在前面的 try 块中遇到一些错误,就会执行 except 块中的代码。

句法:

try:
    # Some Code
except:
    # Executed if error in the
    # try block

try() 是如何工作的?

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

代码 1:无异常,因此try子句将运行。

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)


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, 0)


Python3
# Program to depict else clause with try-except
  
# Function which returns a/b
def AbyB(a , b):
    try:
        c = ((a+b) // (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)
  
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)


Python3
# Python program to demonstrate finally
    
# No exception Exception raised in try block
try:
    k = 5//0 # raises divide by zero exception.
    print(k)
    
# handles zerodivision exception    
except ZeroDivisionError:   
    print("Can't divide by zero")
        
finally:
    # this block is always executed 
    # regardless of exception generation.
    print('This is always executed')


输出 :

('Yeah ! Your answer is :', 1)

代码 1:有一个例外,所以只有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, 0)

输出 :

Sorry ! You are dividing by zero

其他条款

在Python中,您还可以在 try-except 块上使用 else 子句,它必须出现在所有 except 子句之后。只有当 try 子句没有引发异常时,代码才会进入 else 块。

句法:

try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception

代码:

Python3

# Program to depict else clause with try-except
  
# Function which returns a/b
def AbyB(a , b):
    try:
        c = ((a+b) // (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)
  
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

输出:

-5.0
a/b result in 0

Python中的finally关键字

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

句法:

try:
    # Some Code
except:
    # Executed if error in the
    # try block
else:
    # execute if no exception
finally:
    # Some code .....(always executed)

代码:

Python3

# Python program to demonstrate finally
    
# No exception Exception raised in try block
try:
    k = 5//0 # raises divide by zero exception.
    print(k)
    
# handles zerodivision exception    
except ZeroDivisionError:   
    print("Can't divide by zero")
        
finally:
    # this block is always executed 
    # regardless of exception generation.
    print('This is always executed') 

输出:

Can't divide by zero
This is always executed

相关文章:

  • 输出问题
  • Python中的异常处理
  • 用户定义的异常