十五、异常处理
当程序运行过程中出错的时候,捕捉到该错误,并执行一些相应的自定义操作
用法:
try:
expression
except Exception,e:
expression
#try语句有异常发生后执行except
--------------------------------------
--------------------------------------
--------------------------------------
try:
expression
except Exception,e:
expression
finally:
expression
#无论异常是否发生都会执行finally语句块
======================================
======================================
======================================
raise error(message)触发异常
assert condition,message 当condition表达式为false的时候触发一个异常,message为要打印输出的异常信息,触发异常后并终止程序
简要的异常分类举例:
a[1] 如果a没有定义,则触发NameError
>>> a[1]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a[1]
NameError: name 'a' is not defined
------------------------------------------
------------------------------------------
------------------------------------------
a=2;a[1] 此时会触发一个TypeError
>>> a=2;a[1]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
a=2;a[1]
TypeError: 'int' object is not subscriptable
-------------------------------------------
-------------------------------------------
-------------------------------------------
a=[2];a[2] 此时会触发一个IndexError
>>> a=[2];a[2]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a=[2];a[2]
IndexError: list index out of range
-------------------------------------------
-------------------------------------------
-------------------------------------------
a={};a[1] 此时会触发一个KeyError
>>> a={};a[1]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a={};a[1]
KeyError: 1
-------------------------------------------
-------------------------------------------
-------------------------------------------
raise IndexError 触发一个异常
>>> raise IndexError("索引错误了")
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
raise IndexError("索引错误了")
IndexError: 索引错误了
----------------------------------------------
----------------------------------------------
----------------------------------------------
assert False,"error occur" 条件触发一个异常,并打印异常信息
>>> li = [1,2,3,4,5]
>>> assert li[1]==100,"第二个元素不等于100"
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
assert li[1]==100,"第二个元素不等于100"
AssertionError: 第二个元素不等于100
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
try:
li = [1]
print (li[1])
except Exception,e: #e就是那个错误消息,相当于把错误消息赋给e这个变量
print (e)
finally: #无论有没有异常,hello都会被打印出来
print "hello"
---------------------------------------------------------------
---------------------------------------------------------------
---------------------------------------------------------------
try:
li = [30]
print (li[3])
raise IndexError("key Error") #这里我定义了一个索引异常
except KeyError,e: #这里我专门只定义只抓KeyError异常,其他异常我不要,所以上面的Index异常它是不会去抓取的
print (e)