Python的异常处理

Python中的异常类型分如下几种:


1、NameError:尝试访问一个未申明的变量
>>>  v
NameError: name 'v' is not defined

2、ZeroDivisionError:除数为0
>>> v = 1/0
ZeroDivisionError: int division or modulo by zero

3、SyntaxError:语法错误
>>> int int
SyntaxError: invalid syntax (<pyshell#14>, line 1)

4、IndexError:索引超出范围
>>> List = [2]
>>> List[3]
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    List[3]
IndexError: list index out of range

5、KeyError:字典关键字不存在
>>> Dic = {'1':'yes', '2':'no'}
>>> Dic['3']
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    Dic['3']
KeyError: '3'

6、IOError:输入输出错误
>>> f = open('abc')
IOError: [Errno 2] No such file or directory: 'abc'

7、AttributeError:访问未知对象属性
>>> class Worker:
 def Work():
  print("I am working")

>>> w = Worker()
>>> w.a
Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    w.a
AttributeError: 'Worker' object has no attribute 'a'

8、ValueError:数值错误
>>> int('d')

Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    int('d')
ValueError: invalid literal for int() with base 10: 'd'

9、TypeError:类型错误
>>> iStr = '22'
>>> iVal = 22
>>> obj = iStr + iVal;
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    obj = iStr + iVal;
TypeError: Can't convert 'int' object to str implicitly

10、AssertionError:断言错误
>>> assert 1 != 1
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    assert 1 != 1
AssertionError


默认的异常处理器

代码如下:


<span style="font-size:18px;">s = 'Hello girl!'
print s[100]
print 'continue'</span>

如果我们没有对异常进行任何预防,那么在程序执行的过程中发生异常,就会中断程序,调用python默认的异常处理器,并在终端输出异常信息。这种情况下,第3行代码不会执行。

try…except

 代码如下:

<span style="font-size:18px;">s = 'Hello girl!'
try:
 print s[100]
except IndexError:
 print 'error...'
print 'continue'</span>

程序执行到第2句时发现try语句,进入try语句块执行,发生异常,回到try语句层,寻找后面是否有except语句。找到except语句后,会调用这个自定义的异常处理器。except将异常处理完毕后,程序继续往下执行。这种情况下,最后两个print语句都会执行。

except后面也可以为空,表示捕获任何类型的异常。

try…finally

 代码如下:

<span style="font-size:18px;">s = 'Hello girl!'
try:
 print s[100]
finally:
 print 'error...'
print 'continue'</span>

finally语句表示,无论异常发生与否,finally中的语句都要执行。但是,由于没有except处理器,finally执行完毕后程序便中断。这种情况下,倒第2个print会执行,到第1个不会执行。如果try语句中没有异常,三个print都会执行。

assert

 代码如下:

<span style="font-size:18px;">assert False,'error...'
print 'continue'</span>

这个语句,先判断assert后面紧跟的语句是True还是False,如果是True则继续执行print,如果是False则中断程序,调用默认的异常处理器,同时输出assert语句逗号后面的提示信息。本例情况下,程序中断,提示error,后面的print不执行。

with…as

 代码如下:

<span style="font-size:18px;">with open('nothing.txt','r') as f:
 f.read()
 print 2/0
print 'continue'</span>

我们平时在使用类似文件的流对象时,使用完毕后要调用close方法关闭,很麻烦。这里with…as语句提供了一个非常方便的替代方法:open打开文件后将返回的文件流对象赋值给f,然后在with语句块中使用。with语句块完毕之后,会隐藏地自动关闭文件。

如果with语句或语句块中发生异常,会调用默认的异常处理器处理,但文件还是会正常关闭。

这种情况下,会抛出异常,最后的print不执行。






参考:《Python核心编程》

           Python中的异常类型

           Python中的五种异常

          


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值