如何在Python中捕获StandardError异常?\\\\\

如何在Python中捕获StandardError异常?\\\

Exception类是基类,StopIteration、StandardError和Warning都是从它派生出来的。所有的标准错误都是从StandardError派生而来。一些标准错误例如ArithmeticError、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实例没有属性'q'
<type 'exceptions.AttributeError'>
This is an example of StandardError exception

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程