首页 > 学院 > 开发设计 > 正文

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

2019-11-14 17:21:19
字体:
来源:转载
供稿:网友
  • 按自己的方式出错

使用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(":")    PRint x/yexcept ZeroDivisionError:    print "hello exception"#结果如下:>>> :10:25>>> :1:0hello exception

再次引发异常,如

class MuffledCalculator:    muffled = False    def calc(self, expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.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, in calc    return eval(expr)  File "<string>", line 1, in <module>ZeroDivisionError: integer division or modulo by zero>>> clc.muffled = True>>> clc.calc('10/0') #有屏蔽Division by zero is illegal

except后面不带参数可以捕捉所有的异常, 可以通过在ty/except后加一个except语句或者在except语句中用元组将多个异常类型列出来实现捕捉多个异常,如下:

try:    x = input(":")    y = input(":")    print x/yexcept (ZeroDivisionError, TypeError), e:    print e#结果如下>>> :10:0integer division or modulo by zero

 在ty/except后加一个else语句可以在没有引发异常的情况下执行一些语句,如

while True:    try:        x = input(":")        y = input(":")        print x/y    except Exception,e:        print e    else :        print "Ah,.... it successed"        break#结果>>>:10:0integer division or modulo by zero:10:25Ah,.... it successed

finally子句 -- finally子句肯定会被执行,不管try子句中是否发生异常,主要用于关闭文件或者网络套接字。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表