Python标准异常总结:
异常 | 描述 |
---|---|
AssertionError | 断言语句(assert)失败 |
AttributeError | 尝试访问未知的对象属性 |
EOFError | input()读取到EOF却没有接收到任何数据 |
FloatingPointError | 浮点计算错误 |
GeneratorExit | generator.close()方法被调用的时候 |
ImportError | 导入模块失败的时候 |
IndexError | 索引超出序列的范围 |
KeyError | 字典中查找一个不存在的关键字 |
KeyboardInterrupt | 用户输入中断键(ctrl+c) |
MemoryError | 内存溢出(可通删除对象释放内存) |
NameError | 尝试访问一个不存在的变量 |
NotImplementedError | 尚未实现的方法 |
OSError | 操作系统产生的异常 |
OverflowError | 数值运算超出最大限制 |
ReferenceError | 弱引用试图访问一个已经被垃圾回收机制回收了的对象 |
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 | 除数为零 |
实例
- AssertionError
>>> my_list = ["NCEPU"]
>>> assert len(my_list) > 0
>>> my_list.pop()#去掉一个元素
'NCEPU'
>>> assert len(my_list) > 0
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert len(my_list) > 0
AssertionError
>>>
- 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'
>>>
- IndexError
>>> my_list2=[1,2,3]
>>> my_list2[3]
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
my_list2[3]
IndexError: list index out of range
检测异常
1. try-except语句
1)一般形式
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
2) 实例
try:
f=open("Python.txt")
print(f.read())
f.close()
except OSError as reason:
print("文件出错\n错误的原因是:"+str(reason))
结果为:
文件出错
错误的原因是:[Errno 2] No such file or directory: 'Python.txt'
try后跟多个except语句:
try:
sum=1+"1"
f=open("Python100.txt")
print(f.read())
f.close()
except OSError as reason:
print("文件出错\n错误的原因是:"+str(reason))
except TypeError as reason:
print("类型出错\n错误的原因是:"+str(reason))
注:
- try语句检测到异常就不会再执行下面语句,所以上程序只输出类型出错。
- 也可以except (OSError,TypeError):
2. try-finally语句
1)一般形式
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何都会被执行的代码
2)实例
try:
f=open("Python1.txt","w")
print(f.write("存在了"))
sum=1+"1"
except (OSError,TypeError):
print("出错了")
finally
f.close()
3. raise语句
>>>raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
>>>try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
参考文献
https://www.bilibili.com/video/av4050443/?p=34
https://www.runoob.com/python3/python3-errors-execptions.html