📜  Python异常处理

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

Python异常处理

到目前为止,我们已经从第 1 组到第 4 组(第 1 组 | 第 2 组 | 第 3 组 | 第 4 组)探索了基本的Python 。

在本文中,我们将讨论如何在Python中使用 try 处理异常。抓住,最后在适当的例子的帮助下陈述。

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

语法错误和异常之间的区别

语法错误:顾名思义,此错误是由代码中的错误语法引起的。它导致程序的终止。

例子:

Python3
# initialize the amount variable
amount = 10000
 
# check that You are eligible to
#  purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")


Python3
# initialize the amount variable
marks = 10000
 
# perform division with 0
a = marks / 0
print(a)


Python3
# Python program to handle simple runtime error
#Python 3
 
a = [1, 2, 3]
try:
    print ("Second element = %d" %(a[1]))
 
    # Throws error since there are only 3 elements in array
    print ("Fourth element = %d" %(a[3]))
 
except:
    print ("An error occurred")


Python3
# Program to handle multiple errors with one
# except statement
# Python 3
 
def fun(a):
    if a < 4:
 
        # throws ZeroDivisionError for a = 3
        b = a/(a-3)
 
    # throws NameError if a >= 4
    print("Value of b = ", b)
     
try:
    fun(3)
    fun(5)
 
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
    print("ZeroDivisionError Occurred and Handled")
except NameError:
    print("NameError Occurred and Handled")


Python3
# Program to depict else clause with try-except
# Python 3
# 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')


Python3
# Program to depict Raising Exception
 
try:
    raise NameError("Hi there")  # Raise Error
except NameError:
    print ("An exception")
    raise  # To determine whether the exception was raised or not


输出:

异常:当程序语法正确但代码导致错误时引发异常。此错误不会停止程序的执行,但是会改变程序的正常流程。

例子:

Python3

# initialize the amount variable
marks = 10000
 
# perform division with 0
a = marks / 0
print(a)

输出:

在上面的示例中,当我们试图将一个数字除以 0 时引发了 ZeroDivisionError。

注意: Exception 是Python中所有异常的基类。您可以在此处检查异常层次结构。

Try and except 语句——捕捉异常

Try 和 except 语句用于捕获和处理Python中的异常。可以引发异常的语句保存在 try 子句中,处理异常的语句写在 except 子句中。

示例:让我们尝试访问索引超出范围的数组元素并处理相应的异常。

Python3

# Python program to handle simple runtime error
#Python 3
 
a = [1, 2, 3]
try:
    print ("Second element = %d" %(a[1]))
 
    # Throws error since there are only 3 elements in array
    print ("Fourth element = %d" %(a[3]))
 
except:
    print ("An error occurred")
输出
Second element = 2
An error occurred

在上面的例子中,可能导致错误的语句被放置在 try 语句中(在我们的例子中是第二个 print 语句)。第二个打印语句尝试访问列表中不存在的第四个元素,这会引发异常。然后这个异常被 except 语句捕获。

捕获特定异常

一条 try 语句可以有多个 except 子句,以指定不同异常的处理程序。请注意,最多将执行一个处理程序。例如,我们可以在上面的代码中添加 IndexError。添加特定异常的一般语法是 -

try:
    # statement(s)
except IndexError:
    # statement(s)
except ValueError:
    # statement(s)

示例:在Python中捕获特定异常

Python3

# Program to handle multiple errors with one
# except statement
# Python 3
 
def fun(a):
    if a < 4:
 
        # throws ZeroDivisionError for a = 3
        b = a/(a-3)
 
    # throws NameError if a >= 4
    print("Value of b = ", b)
     
try:
    fun(3)
    fun(5)
 
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
    print("ZeroDivisionError Occurred and Handled")
except NameError:
    print("NameError Occurred and Handled")
输出
ZeroDivisionError Occurred and Handled

如果您对 fun(3) 行发表评论,则输出将是

NameError Occurred and Handled

上面的输出是这样的,因为一旦Python尝试访问 b 的值,就会发生 NameError。

尝试使用其他条款

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

示例:尝试使用 else 子句

Python3

# Program to depict else clause with try-except
# Python 3
# 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:
    # optional block
    # Handling of exception (if required)

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

引发异常

raise 语句允许程序员强制发生特定的异常。 raise 中的唯一参数表示要引发的异常。这必须是异常实例或异常类(从 Exception 派生的类)。

Python3

# Program to depict Raising Exception
 
try:
    raise NameError("Hi there")  # Raise Error
except NameError:
    print ("An exception")
    raise  # To determine whether the exception was raised or not

上述代码的输出将简单地打印为“异常”,但由于最后一行中的 raise 语句,最后也会出现运行时错误。因此,命令行上的输出看起来像

Traceback (most recent call last):
  File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in 
    raise NameError("Hi there")  # Raise Error
NameError: Hi there

https://youtu.be/fCRB8ADbBSc