按自己的方式出错使用raise语句引发一个异常,可以使用一个类(应该是Exception的子类)或者实例参数来作为raise的引发对象。使用类时,程序会自动创建实例,如
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
raise Exception('hyperdrive overload')
Exception: hyperdrive overload
捕捉异常可以使用try/except实现捕捉异常,如
try:
x= input(":")
y= input(":")PRintx/yexceptZeroDivisionError:print"hello exception"#结果如下:>>>:10:2
5
>>>:1:0
hello exception
再次引发异常,如
classMuffledCalculator:
muffled=Falsedefcalc(self, expr):try:returneval(expr)exceptZeroDivisionError:ifself.muffled :#如果屏蔽标志开启,则处理异常print"Division by zero is illegal"else:#如果屏蔽标志未开启,则再次引发异常raise#结果如下:>>> clc =MuffledCalculator()>>> clc.calc('10/2')5
>>> clc.calc('10/0')#没有屏蔽Traceback (most recent call last):
File"<pyshell#17>", line 1,in<module>clc.calc('10/0')#没有屏蔽File"E:\work\Code\python\test.py", line 137,incalcreturneval(expr)
File"<string>", line 1,in<module>ZeroDivisionError: integer divisionormodulo by zero>>> clc.muffled =True>>> clc.calc('10/0')#有屏蔽Division by zeroisillegal
except后面不带参数可以捕捉所有的异常, 可以通过在ty/except后加一个except语句或者在except语句中用元组将多个异常类型列出来实现捕捉多个异常,如下:
try:
x= input(":")
y= input(":")printx/yexcept(ZeroDivisionError, TypeError), e:printe#结果如下>>>:10:0
integer divisionormodulo by zero
在ty/except后加一个else语句可以在没有引发异常的情况下执行一些语句,如
whileTrue:try:
x= input(":")
y= input(":")printx/yexceptException,e:printeelse:print"Ah,.... it successed"
break#结果>>>:10:0
integer divisionormodulo by zero
:10:2
5Ah,.... it successed
finally子句 -- finally子句肯定会被执行,不管try子句中是否发生异常,主要用于关闭文件或者网络套接字。