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 | 除数为零 |
异常检测和处理
第一种
try:
检测范围
except Exception [as reason]:
出现异常(Exception)后的处理代码
try:
f = open('E:\\Tt.txt')
print(f.read())
f.close()
except OSError:
print('文件出错了T_T')
>>> ================================ RESTART ================================
>>>
文件出错了T_T
>>>
try:
f = open('E:\\Tt.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件出错了T_T\n错误的原因:'+str(reason))
>>>
文件出错了T_T
错误的原因:[Errno 2] No such file or directory: 'E:\\Tt.txt'
>>>
try:
sum = 1 + '1'
f = open('E:\\Tt.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件出错了T_T\n错误的原因:'+str(reason))
except TypeError as reason:
print('类型出错了T_T\n错误的原因:'+str(reason))
>>>
类型出错了T_T
错误的原因:unsupported operand type(s) for +: 'int' and 'str'
>>>
把多个异常合为一个元组
try:
#sum = 1 + '1'
f = open('E:\\Tt.txt')
print(f.read())
f.close()
except (OSError,TypeError) as reason:
print('出错了T_T\n错误的原因:'+str(reason))
第二种
try:
检测范围
except Exception [as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何都会执行的代码
try:
f = open('E:\\Tt.txt','w')
print(f.write('我存在!'))
sum = 1 + '1'
except (OSError,TypeError) as reason:
print('出错了T_T\n错误的原因:'+str(reason))
finally:
f.close()
>>>
4
出错了T_T
错误的原因:unsupported operand type(s) for +: 'int' and 'str'
>>>
程序报错了,但数据还是保存在了文件中。
第三种
关键字:raise
>>> raise
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise
RuntimeError: No active exception to reraise
>>>
>>> 1/0
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
1/0
ZeroDivisionError: division by zero
>>> raise ZeroDivisionError('除数不能为零!')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
raise ZeroDivisionError('除数不能为零!')
ZeroDivisionError: 除数不能为零!
>>>