Python异常处理

到目前为止,我们已经从第1集到第4集探索了基本python( 第一组 | 第二组 | 第三组 | 第四组 ).

null

在本文中,我们将讨论如何使用try处理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" )


输出:

图片[1]-Python异常处理-yiteyi-C++库

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

例子:

Python3

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


输出:

图片[2]-Python异常处理-yiteyi-C++库

在上面的例子中,当我们试图将一个数字除以0时,出现了ZeroDivision错误。

注: 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 = 2An error occurred

在上面的示例中,可能导致错误的语句放在try语句中(在我们的例子中是第二个print语句)。第二个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。

试用Else子句

在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.0a/b result in 0 

Python中的Finally关键字

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

语法:

try:    # Some Code.... except:    # optional block    # Handling of exception (if required)else:    # execute if no exceptionfinally:    # 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 zeroThis is always executed

提出例外

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

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 <module>    raise NameError("Hi there")  # Raise ErrorNameError: Hi there

https://youtu.be/fCRB8ADbBSc

本文由 尼希尔·库马尔·辛格 (nickzuck_007)

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享