032异常处理:你不可能总是对的
1.AssertionError:断言语句(assert)失败>>> my_list = ['小甲鱼是帅哥']
>>> assert len(my_list) > 0
>>> my_list.pop()
'小甲鱼是帅哥'
>>> assert len(my_list) > 0
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert len(my_list) > 0
AssertionError
2.AttributeError:尝试访问未知的对象属性
>>> my_list.fishc
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
3.IndexError:索引超出序列范围
>>> my_list =
>>> my_list
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
my_list
IndexError: list index out of range
>>> my_list
3
4.KeyError:字典中查找一个不存在的关键字
>>> my_dict = {'one':1, 'two':2, 'three':3}
>>> my_dict['one']
1
>>> my_dict['four']
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
my_dict['four']
KeyError: 'four'
5.NameError:尝试访问一个不存在的变量
>>> fishc
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
fishc
NameError: name 'fishc' is not defined
6.OSError:操作系统产生的异常(例如打开一个不存在的文件)
file_name = input('请输入需要打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
print(each_line)
========== RESTART: F:\BaiduYunDownload\《零基础入门学习Python》\py\032-1.py ==========
请输入需要打开的文件名:record
Traceback (most recent call last):
File "F:\BaiduYunDownload\《零基础入门学习Python》\py\032-1.py", line 2, in <module>
f = open(file_name)
FileNotFoundError: No such file or directory: 'record'
7.SyntaxError:Python的语法错误
>>> print 'I love FishC.com'
SyntaxError: Missing parentheses in call to 'print'
>>> print('I love FishC.com')
I love FishC.com
8.TypeError:不同类型间的无效操作
>>> 1 + '1'
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
9.ZeroDivisionError:除数为零
>>> 5 / 0
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
5 / 0
ZeroDivisionError: division by zero
页:
[1]