0.说明
如果想写出用户体验高的代码,那么就需要考虑到在执行自己写的这段代码中在和用户交互的过程中可能会出现的问题,也就是说,需要对可能出现的异常进行处理,只有做好这些工作,才能写出用户体验好的代码。
1.什么是异常
错误
错误是语法(导致解释器无法解释)或逻辑(也就是代码质量问题)上的,在Python中,当检测到错误时,解释器会指出当前流无法继续执行下去,于是就出现了异常。
异常
程序出现了错误而在正常控制流以外采取的行为。
根据上面的解释,可以理解为,只要解释器检测到程序运行时出现了错误(与Python解释器不相容而导致),就会触发一个异常。
2.Python中的异常
如下:
异常类型 | 描述 | 简单例子 |
NameError | 尝试访问一个未声明的变量,或者是在名称空间中不存在的变量 | >>> xpleaf Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ‘xpleaf‘ is not defined |
ZeroDivisionError | 除数为零 | >>> 1/0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero |
SyntaxError | Python解释器语法错误 (唯一不是在运行时发生的异常,发生在编译时,Python解释器无法把相关脚本编译为Python字节代码) | >>> for File "<stdin>", line 1 for ^ SyntaxError: invalid syntax |
IndexError | 请求的索引走出序列范围 | >>> aList = [] >>> aList[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range |
KeyError | 请求一个不存在的字典关键字 | >>> aDict = {‘name‘: ‘xpleaf‘, ‘love‘: ‘cl‘} >>> aDict[‘clyyh‘] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: ‘clyyh‘ |
IOError | 输入/输出错误 (任何类型的I/O错误都会引发IOError异常) | >>> f = open(‘xpleaf‘) Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: ‘xpleaf‘ |
AttributeError | 尝试访问未知的对象属性 | >>> class myClass(object): ... pass ... >>> myInst = myClass() >>> myInst.name Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: ‘myClass‘ object has no attribute ‘name‘ |
本文出自 “香飘叶子” 博客,请务必保留此出处http://xpleaf.blog.51cto.com/9315560/1762213
原文地址:http://xpleaf.blog.51cto.com/9315560/1762213