如何在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 寒露祝福语毕业寄语简短