如何在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短