python中常见的异常 error

python中常见的异常

在python2中可以通过一个模块来查看所有的内置异常,而在python3中就无法查看。

>>> importexceptions>>>dir(exceptions)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']

下面介绍介几个使用的比较频繁的异常。

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

>>>foo

Traceback (most recent call last):

File"", line 1, in NameError: name'foo' is not defined

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

任何可访问的变量必须在名称空间里列出,访问变量需要由解释器进行搜索,如果请求的名字没有在任何名称空间里找到,那么就会生成一个NameError异常。

2.ZeroDivisionError:除数为0.

>>> 1/0

Traceback (most recent call last):

File"", line 1, in ZeroDivisionError: division by zero

任何一个数值被零除都会导致ZeroDivisionError异常。

3.SyntaxError:python解释器语法错误。

>>> for i inli:

...printi

File"", line 2

printi^SyntaxError: Missing parenthesesin call to 'print'. Did you mean print(i)?

SyntaxError异常是唯一不是在运行时发生的异常。

它代表python代码中有一个不正确的结构,在他改正之前程序无法运行。

这些错误一般都是在编译时发生的,python解释器无法把你的脚本转化成python字节代码。

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

>>>li

[1, 2, 3, 4]>>> li[10]

Traceback (most recent call last):

File"", line 1, in IndexError: list index out of range

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

>>> dict1 = {"name":'kebi',"sex":'boy'}>>> dict1['age']

Traceback (most recent call last):

File"", line 1, in KeyError:'age'

6.IOError/FileNotFoundError:输入/输出错误

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

在python2中引发IOError异常;在python3中引发/FileNotFoundError异常。

#在python2中

>>> f = open('helo')

Traceback (most recent call last):

File"", line 1, in IOError: [Errno2] No such file or directory: 'helo'

#在python3中

>>> f = open('blah')

Traceback (most recent call last):

File"", line 1, in FileNotFoundError: [Errno2] No such file or directory: 'blah'

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

>>> classmyClass(object):

...pass...>>> myInst =myClass()>>>myInst.foo

Traceback (most recent call last):

File"", line 1, in AttributeError:'myClass' object has no attribute 'foo'

posted @ 2024-02-22 11:25  朱饱饱  阅读(88)  评论(0)    收藏  举报