|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 只为 于 2017-9-10 13:01 编辑
1、Exception
程序出现逻辑错误或者用户输入不合法都会引发错误,但这些错误并不是致命的,不会导致程序崩溃死掉。我们完全可以利用Python提供的异常机制,在错误出现的时候,程序可以内部自我消化掉。
2、Python标准异常总结
(小甲鱼链接:http://bbs.fishc.com/forum.php?m ... peid%26typeid%3D403)
1)AssertionError:断言语句(assert)失败
注:
i.当assert后的条件为False时,程序自动抛出该异常(第八讲提到过?)
ii.assert语句的用途主要是用于测试中,测试某个点
- >>> assert 0
- Traceback (most recent call last):
- File "<pyshell#0>", line 1, in <module>
- assert 0
- AssertionError
复制代码
2)AttributeError:尝试访问未知的对象属性(或者方法)
- >>> list1 = []
- >>> list1.fishc()
- Traceback (most recent call last):
- File "<pyshell#3>", line 1, in <module>
- list1.fishc()
- AttributeError: 'list' object has no attribute 'fishc'
复制代码
3)IndexError:索引超出序列的范围
4)KeyError:字典众查找一个不存在的关键字
- >>> my_dict = {'one':1,'two':2,'three':3}
- >>> my_dict['one']
- 1
- >>> my_dict['four']
- Traceback (most recent call last):
- File "<pyshell#6>", line 1, in <module>
- my_dict['four']
- KeyError: 'four'
- >>> my_dict.get('four')
- >>>
复制代码
注:字典中通过key取值时,可以使用get方法,防止KeyError异常
5)NameError:尝试访问一个不存在的变量
- >>> a
- Traceback (most recent call last):
- File "<pyshell#8>", line 1, in <module>
- a
- NameError: name 'a' is not defined
复制代码
6)OSError:操作系统产生的异常(例如打开一个不存在的文件)
- >>> open('s.txt')
- Traceback (most recent call last):
- File "<pyshell#9>", line 1, in <module>
- open('s.txt')
- FileNotFoundError: [Errno 2] No such file or directory: 's.txt'
复制代码
注:FileNotFoundError 属于OSError一种
7)OverflowError:数值运算超出了最大限制
注:python中一般不会出现,python可以接收很大的数据
8)SyntaxError:Python的语法错误
- >>> print 'i love fishc'
- SyntaxError: Missing parentheses in call to 'print'
复制代码
注:Python3中print()是一个函数
9)TypeError:不同类型间的无效操作
- >>> 1 + '1'
- Traceback (most recent call last):
- File "<pyshell#1>", line 1, in <module>
- 1 + '1'
- TypeError: unsupported operand type(s) for +: 'int' and 'str'
复制代码
10)ZeroDivisionError:除数为零
- >>> 1/0
- Traceback (most recent call last):
- File "<pyshell#2>", line 1, in <module>
- 1/0
- ZeroDivisionError: division by zero
复制代码
3、补充Exception
1)TabError:Tab和空格混用使用
2)UnicodeError:Unicode相关的错误(ValueError的子类)
3)ValueError:传入无效的参数
4)FileExistsError:文件已存在错误
5)PermissionError:没有打开文件的权限
4、Python内置异常类的层次结构
提示:Exception包括Warning |
|