如何在Python中捕获StandardError异常?
有一个Exception类,它是StopIteration,StandardError和Warning的基类。所有标准错误均源自StandardError。某些标准错误(例如ArithmeticErrror,AttributeError,AssertionError)从基类StandardError派生。
当属性引用或分配失败时,将引发AttributeError。例如,当尝试引用不存在的属性时:
我们重写给定的代码并捕获异常并知道其类型。
示例
import sys try: class Foobar: def __init__(self): self.p = 0 f = Foobar()print(f.p) print(f.q) except Exception as e: print e print sys.exc_type print 'This is an example of StandardError exception'
输出结果
0 Foobar instance has no attribute 'q' <type 'exceptions.AttributeError'> This is an example of StandardError exception
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志