异常
异常 | 原因 |
---|
AssertionError | 判断语句(assert)失败 |
AttributeError | 尝试访问未知的对象属性 |
EOFError | input()读取到EOF却没有接收任何数据 |
FloatingPointError | 浮点数计算错误 |
GeneratorExit | generator.close()方法被调用的时候 |
ImportError | 导入模块失败的时候 |
IndexError | 索引超出序列的范围 |
KeyError | 字典中查找-一个不存在的关键字 |
KeyboardInterrupt | 用户输入中断健(Crl+c) |
MemoryError | 内存溢出(可通过删除对象释放内存) |
NameError | 尝试访问一个不存在的变量 |
NotimplementedError | 尚未实现的方法 |
OSError | 操作系统产生的异常(例如打开-个不存在的文件 ) |
OverflowError | 数值运算超出最大限制 |
ReferenceError | 弱引用( weak reference )试图访问一个已经被垃圾回收机制回收了的对象 |
RuntimeError | 一般的运行时错误 |
StopIteration | 迭代器没有更多的值 |
SyntaxError | Python的语法错误 |
IndentationError | 缩进错误 |
TabError | Tab和空格混合使用 |
SystemError | Python编译器系統错误 |
SystemExit | Python编译鼹进程被关闭 |
TypeError | 不同类型间的无效操作 |
UnboundLocalError | 访问一个未初始化的本地变量( NameError的子类) |
UnicodeEncodeError | Unicode相关的错误( ValueError的子类) |
UnicodeDncodeError | Unicode解码时的错误( UnicodeError的子类) |
UnicodeTranslateError | Unicode转换时的错误( UnicodeError的子美) |
ValueError | 传入无效的参数 |
ZeroDivisionError | 除数为零 |
list1 = [1]
assert len(list1) > 0
list1.pop()
1
assert len(list1) > 0
NameError Traceback (most recent call last)
<ipython-input-1-06cfd067d119> in <module>
----> 1 assert len(list1) > 0
NameError: name 'list1' is not defined
list1.ffsakf
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-b3cb545c998e> in <module>
----> 1 list1.ffsakf
AttributeError: 'list' object has no attribute 'ffsakf'
'''
try:
检测访问
except Exception[as reason]:
出现异常(Exception)后的处理代码
finally:
无论如何都会被执行的代码
'''
try:
s = 1 + '1'
fsadf
except NameError as reason:
print('出错了,原因:'+ str(reason))
except TypeError as reason:
print('出错了,原因:' + str(reason))
出错了,原因:unsupported operand type(s) for +: 'int' and 'str'
try:
s = 1 + '1'
fsadf
except:
print('出错了')
出错了
try:
s = 1 + '1'
fsadf
except (TypeError, NameError):
print('出错了')
出错了
raise
- 这个语句就是把已知的错误重新定义出错原因
raise TypeError('5545446')
TypeError Traceback (most recent call last)
<ipython-input-26-013431d31575> in <module>
----> 1 raise TypeError('5545446')
TypeError: 5545446
try:
a = input("输入一个数:")
if(not a.isdigit()):
raise ValueError("a 必须是数字")
except ValueError as e:
print("引发异常:",repr(e))
输入一个数:e
引发异常: ValueError('a 必须是数字')