菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
425
0

python进阶(5)异常模块

原创
05/13 14:22
阅读数 29673

异常模块

下面介绍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"<pyshell#14>", line1, in <module>
        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"<pyshell#20>", line1, in <module>
        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"<pyshell#22>", line1, in <module>
        print(5 / int(i))
ValueError: invalid literal for int() with base 10: 'QWE'

发表评论

0/200
425 点赞
0 评论
收藏
为你推荐 换一批