Python中的异常

来源:互联网 发布:淘宝网大码女装店连衣裙 编辑:程序博客网 时间:2024/06/07 18:22

Python中的异常

1. NameError:尝试访问一个未申明的变量

>>> foo
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    foo
NameError: name 'foo' is not defined

NameError表示我们访问了一个没有初始化的变量。


2.ZeroDivisionError:除数为零

>>> 1/0
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero

这里的例子举的是是使用整数。事实上,任何一个数被零除都会导致一个ZeroDivisionError异常。


3.SyntaxError :Python解释器语法错误

>>> for
SyntaxError: invalid syntax

.SyntaxError异常是唯一不是在运行时发生的异常。它代表Python代码中有一个不正确的结构,在它改正之前程序无法执行。


4.IndexError:请求的索引超出序列范围

>>> aList=[]
>>> aList[0]
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    aList[0]
IndexError: list index out of range

IndexError在你尝试使用一个超出范围的值索引序列时发生。


5.KeyError:请求一个不存在的字典关键字

>>> aDict = {'host': 'earth','port': '80'}
>>> print(aDict['server'])
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    print(aDict['server'])
KeyError: 'server'


映射对象,例如字典,是依靠关键字(key)访问数据值得。

如果使用错误的或是不存在的键请求字典就会引发一个KeyError异常。


6.IOError:输入输出错误

>>> f=open("blan")
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    f=open("blan")
FileNotFoundError: [Errno 2] No such file or directory: 'blan'

类似尝试打开一个不存在的磁盘文件一类的操作会引发一个操作系统输入|输出(I|O)错误。

任何类型的I\O错误都会引发IOError异常。


7.AttributeError:尝试访问未知的对象属性

>>> myInst = myClass()
>>> myInst.bar = 'spam'
>>> myInst.bar
'spam'
>>> myInst.foo
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    myInst.foo
AttributeError: 'myClass' object has no attribute 'foo'

在我的例子中,在myInst.bar存储了一个值,也就是实例myInst的Bar属性。

属性被定义后,我们可以使用熟悉的点/属性操作符访问他。但是如果属性没有定义,我们访问foo属性,将导致一个AttributeError异常。