python进阶(5)异常模块
发布日期:2021-05-09 03:53:27 浏览次数:18 分类:博客文章

本文共 1037 字,大约阅读时间需要 3 分钟。

异常模块

下面介绍python常用的异常模块

 

AttributeError异常

AttributeError试图访问一个类中不存在的成员(包括:成员变量、属性和成员方法)而引发的异常

AttributeError:'Animal' object has no attribute 'age'

 

OSError异常

OSError是操作系统相关异常

FileNotFoundError:[Error 2] No such file or directory: 'abc.txt'

 

IndexError异常

IndexError异常是访问序列元素时,下标索引超出取值范围所引发的异常

IndexError: list index out of range

 

KeyError异常

KeyError异常是试图访问字典里不存在的键时而引发的异常

>>> dict[104]Traceback(most recent call last):    File"
", line1, in
dict1[104]KeyError: 104

 

NameError异常

NameError是试图使用一个不存在的变量而引发的异常

NameError: name 'value1' is not defined

 

TypeError异常

TypeError是试图传入变量类型与要求的不符合时而发生的异常

>>> i = '2'>>> print(5 / i)Traceback(most recent call last):    File"
", line1, in
print(5 / i)TypeError: unsupported operand type(s) for /: 'int' and 'str'

 

ValueError异常

ValueError异常是由于传入一个无效的参数值而引发的异常

>>> i = 'QWE>>> print(5 / int(i))Traceback(most recent call last):    File"
", line1, in
print(5 / int(i))ValueError: invalid literal for int() with base 10: 'QWE'
上一篇:python进阶(6)深拷贝和浅拷贝
下一篇:python进阶(4)文件操作

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月01日 12时01分04秒