Python的异常

常见异常

异常 描述
NameError 尝试访问一个没有申明的变量
ZeroDivisionError 除数为0
SyntaxError 语法错误
IndexError 索引超出序列范围
KeyError 请求一个不存在的字典关键字
IOError 输入输出错误(例如要读取的文件不存在 )
AttributeError 尝试访问位置的对象属性

简单介绍下

NameError

wxx
变量没有初始化,即没有赋值。因为变量相当于一个标签,要将其贴到对象上才有意义。

>>> wxx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'wxx' is not defined

ZeroDivisionError

除数为0

>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

SyntaxError

语法错误,编译时无法正确转化为Python字节码,故报错,只有修改正确之后才能编译成功。

>>> def func()
  File "<stdin>", line 1
    def func()
             ^
SyntaxError: invalid syntax

IndexError

索引超过范围。这个道理告诉我们充大头鬼需要付出代价。

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> f = range(10)
>>> f[11]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

KeyError

如果字典中不存在该关键字,报错。纯属无中生有了。

>>> dic = {'name':'wxx','age':'23'}
>>> dic['height']
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: 'height'

IOError

文件不存在。怎么可能有这个文件。

>>> file = open("nvyou.avi")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'nvyou.avi'

AttributeError

属性不存在,纯属无中生有。

>>> def func():
...     a = 1
... 
>>> fu = func()
>>> fu.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'b'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • python中常见的异常 NameError:尝试访问一个未申明的变量 ZeroDivisionError:除数为...
    junson阅读 492评论 0 1
  • 在执行程序的过程中,可能会遇到多多少少的“意外情况”,比如除数为 0,文件找不到,变量未声明等。解释器在发现这些异...
    柏丘君阅读 1,039评论 0 1
  • assert 从上面的举例中可以基本了解了 assert 的特点。assert,翻译过来是“断言”之意。asser...
    上发条的树阅读 248评论 0 0
  • Python 的运行时错误称作异常 语法错误:软件结构上有错误而导致不能被解释器解释或不能被编译器编译逻辑错误:...
    魔法高校的劣等生阅读 254评论 0 0
  • 1.事务 2.事务并发问题 3.事务的隔离级别 4.如何在hibernate中指定数据库的隔离级别 5、在项目中如...
    Explorer_Mi阅读 232评论 0 1