python expect模块_Python异常处理

0b695c2ec24717382c3c274af32a4a1a.png

像其他语言一样,python通过try-except提供了运行时错误异常处理方法。 一些最常见的标准异常包括IndexError,ImportError,IOError,ZeroDivisionError,TypeError。

Exception是python中所有异常的基类。您可以在此处检查异常层次结构(https://docs.python.org/2/library/exceptions.html#exception-hierarchy)。

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

# 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 IndexError:     print "An error occurred"

输出:

Second element = 2An error occurred

一个try语句可以具有一个以上的except子句,以指定不同异常的处理程序。请注意,最多将执行一个处理程序。

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

输出:

Error Occurred and Handled

如果您将“a”的值更改为大于或等于4,则输出为

Value of b =  Error Occurred and Handled

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

Else子句:

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

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

引发异常:

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

# 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 

上面代码的输出将简单地打印为“An exception”,但是由于最后一行中的raise语句,最后也会发生运行时错误。因此,命令行上的输出将如下所示

Traceback (most recent call last):  File "003dff3d748c75816b7f849be98b91b8.py", line 4, in     raise NameError("Hi there") # Raise ErrorNameError: Hi there
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值