Python – 捕获所有异常
在本文中,我们将通过适当的示例讨论如何使用 try, except 语句捕获Python中的所有异常。但在此之前,让我们看看Python中不同类型的错误。
Python中通常有两种类型的错误,即语法错误和异常。让我们看看它们之间的区别。
语法错误和异常之间的区别
语法错误:顾名思义,此错误是由代码中的错误语法引起的。它导致程序的终止。
示例: 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
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 ("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")
输出:
SyntaxError: invalid syntax
异常:当程序语法正确但代码导致错误时引发异常。此错误不会停止程序的执行,但是会改变程序的正常流程。
示例: Python中的异常
Python3
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
输出:
ZeroDivisionError: division by zero
Try and except 语句——捕获所有异常
Try 和 except 语句用于捕获和处理Python中的异常。可以引发异常的语句保存在 try 子句中,处理异常的语句写在 except 子句中。
示例: Python捕获所有异常
Python3
# Python program to handle simple runtime error
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 ("Error occurred")
Second element = 2
An error occurred
在上面的例子中,可能导致错误的语句被放置在 try 语句中(在我们的例子中是第二个 print 语句)。第二个打印语句尝试访问列表中不存在的第四个元素,这会引发异常。然后这个异常被 except 语句捕获。在不指定任何类型的异常的情况下,try 块中的所有异常都将被 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异常处理教程。