如何在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 红包祝福语简短10字
18 周六早晨祝福语简短