《python基础教程》笔记之异常

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

按自己的方式出错使用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子句中是否发生异常,主要用于关闭文件或者网络套接字。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航