如何在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 鼓励孩子小考祝福语简短