对于我们写程序的人来说,出现错误是避免不了,如果我们在写程序的过程中出现了错误,我建议每一位写程序的人,先从自己身上找错误,不要总是觉得自己是对的,这样很不好,不利于我们找到错误,也不利于我们的成长。
下面举一个列子 :
我们写一个读取文件内容的程序:
file_name= input('请输入一个文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
print(each_line)
运行之后我们输入一个文件名(不加后缀)之后python就会给出异常的 类型:
请输入一个文件名:test
Traceback (most recent call last):
File "D:\Python\test\test.py", line 2, in <module>
f = open(file_name)
FileNotFoundError: [Errno 2] No such file or directory: 'test'
>>>
Python提醒我们这个文件不存在,如果我们加上后缀名,就可以顺利的打开。
下面列举一下常见的异常:
AssertionError | 断言语句(assert)失败 |
AttributeError | 尝试访问未知的对象属性 |
EOFError | 用户输入文件末尾标志EOF(Ctrl+d |
FloatingPointError | 浮点计算错误 |
GeneratorExit | generator.close()方法被调用的时候 |
ImportError | 导入模块失败的时候 |
IndexError | 索引超出序列的范围 |
KeyError | 字典中查找一个不存在的关键字 |
KeyboardInterrupt | 用户输入中断键(Ctrl+c) |
MemoryError | 内存溢出(可通过删除对象释放内存) |
NameError | 尝试访问一个不存在的变量 |
NotImplementedError | 尚未实现的方法 |
OSError | 操作系统产生的异常(例如打开一个不存在的文件) |
OverflowError | 数值运算超出最大限制 |
ReferenceError | 弱引用(weak reference)试图访问一个已经被垃圾回收机制回收了的对象 |
RuntimeError | 一般的运行时错误 |
StopIteration | 迭代器没有更多的值 |
SyntaxError | Python的语法错误 |
IndentationError | 缩进错误 |
TabError | Tab和空格混合使用 |
SystemError | Python编译器系统错误 |
SystemExit | Python编译器进程被关闭 |
TypeError | 不同类型间的无效操作 |
UnboundLocalError | 访问一个未初始化的本地变量(NameError的子类) |
UnicodeError | Unicode相关的错误(ValueError的子类) |
UnicodeEncodeError | Unicode编码时的错误(UnicodeError的子类) |
UnicodeDecodeError | Unicode解码时的错误(UnicodeError的子类) |
UnicodeTranslateError | Unicode转换时的错误(UnicodeError的子类) |
ValueError | 传入无效的参数 |
ZeroDivisionError | 除数为零 |
列举出来并不是为了记住,而是碰到的时候可以查看
针对上面的一些异常举例:
>>> list1 = ['xiaoyi']
>>> assert len(list1) > 0
>>> list1.pop()
'xiaoyi'
>>> assert len(list1) > 0
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
assert len(list1) > 0
AssertionError
>>> list2 = [1,2,3]
>>> list2[3]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
list2[3]
IndexError: list index out of range
>>> dict1 = {'one':1,'two':2}
>>> dict1['three']
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
dict1['three']
KeyError: 'three'
>>> dict1.get('three')
>>> dict1.get('one')
1
>>> abc
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
abc
NameError: name 'abc' is not defined
>>> print 'xioayi'
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('xioayi')?
>>> 1 + '1'
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 6 / 0
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
6 / 0
ZeroDivisionError: division by zero
>>>
为了减少我们的异常或者说是检测异常我们会在程序中使用异常检测语句:
1、try -except语句
语句模式:
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
try:
f = open('xiaoyi.text')
print(f.read())
f.close()
except OSError:
print('文件出错')
当然我们也可以打印出出错的原因:
try:
f = open('xiaoyi.text')
print(f.read())
f.close()
except OSError as reason:
print('文件出错\n错误的原因是:' + str(reason))
我们看一下运行结果:
文件出错
错误的原因是:[Errno 2] No such file or directory: 'xiaoyi.text'
>>>
当然一个人try也是可以和多个except配合使用的:
try:
sum = 1 + '1'
f = open('xiaoyi.text')
print(f.read())
f.close()
except OSError as reason:
print('文件出错\n错误的原因是:' + str(reason))
except TypeError as reason:
print('类型出错\n错误的原因是:' + str(reason))
我们看一下这个运行结果:
类型出错
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
>>>
从这两个运行结果中我们可以看出try语句一旦遇到一个错误下面的代码就不会执行了。
还有一种写法也是可以的:
try:
sum = 1 + '1'
f = open('xiaoyi.text')
print(f.read())
f.close()
except (OSError,TypeError):
print('出错\n')
2、try - finally语句
语句格式:
try:
检测范围
except Exception [as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何人都会被执行的代码
try:
f = open('xiaoyi.text' ,'w')
print(f.write('创建成功'))
sum = 1 + '1'
f.close()
except (OSError,TypeError):
print('出错\n')
finally:
f.close()
从上面的代码我们可以看出,如果我们没有写finally语句的话,是不能将内容写到文件中的,因为try后面的关闭文件语句close是执行不了的,这样我们写的内容就一直在缓冲区中,只有关闭文件才会写到文件中,finally帮助我们做到了。
我们也可以使用raise引出一个异常:
>>> raise ZeroDivisionError
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError ('除数异常')
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
raise ZeroDivisionError ('除数异常')
ZeroDivisionError: 除数异常
>>>
try语句也是可以配合else使用的 :
try:
int('abc')
except ValueError as reason:
print('出错了\n异常是:' + str(reason))
else:
print('没有出现异常 ')
使用with语句可以简化我们的代码 :
try:
with open('xiaoyi.text' ,'w') as f:
for each_line in f:
print(each_line)
except OSError:
print('出错\n')
finally:
f.close()