>>>foo
Traceback (most recent call last):
File "", line 1, in
foo
NameError: name 'foo' is not defined
如果请求的名字没有在任何名称空间里找到,则产生一个NameError异常。 2、ZeroDivisionError:除数为0
>>> 1/0
Traceback (most recent call last):
File "", line 1, in
1/0
ZeroDivisionError: integer division or modulo by zero 3、SyntaxError:Python解释器语法错误
>>> for
SyntaxError: invalid syntax
>>>
SyntaxError异常是唯一一个不是在程序执行时发生的异常,代表一个不正常的结构,一般在编译时发生。 注意:Python是解释型非编译型,这里说的编译是字节编译。 4、IndexError:超出索引( out of range)
>>> lis = []
>>> lis[0]
Traceback (most recent call last):
File "", line 1, in
lis[0]
IndexError: list index out of range 5、KeyError:请求一个不存在的字典关键字
>>> f = open('s.txt','r')
Traceback (most recent call last):
File "", line 1, in
f = open('s.txt','r')
IOError: [Errno 2] No such file or directory: 's.txt' 7、AttributeError:尝试访问未知的属性
>>> class myClass(object):
pass
>>> myIn = myClass()
>>> myIn.bar
Traceback (most recent call last):
File "", line 1, in
myIn.bar
AttributeError: 'myClass' object has no attribute 'bar'
>>> 8、ValueError:传给函数的参数类型不正确,比如给int()函数传入字符串形
三、异常处理
try-except/try-finally只選其一,可以一个try多个except;但只能一个try,一个finally
try-except-finally组合
try:
assert 1 == 2,'1 is not equal 2'
except Exception,e:
print '%s:%s' %(e.__class__.__name__,e)
#输出:AssertionError:1 is not equal 2
注意:
如果上面的with代码块没有使用from __future__ import with_statement, 代码将会报错, 提示你这个功能在2.6中实现.
Warning: 'with' will become a reserved keyword in Python 2.6