Python异常及处理
目录
Python内置异常类的层次结构
Python异常处理
try 语句
try-except 语句
try-finally 语句
raise 语句
else 语句
with 语句
Python内置异常类的层次结构
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
AssertionError
断言语句(assert)失败。assert 语句后条件为假时,程序自动崩溃并抛出 AssertionError 的异常。
一般用它在程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作时,assert 关键字就非常有用。
>>> assert 3 < 4
>>> assert 4 < 3
Traceback (most recent call last):File "<pyshell#12>", line 1, in <module>assert 4 < 3
AssertionError
>>> my_list = ['ABC']
>>> assert len(my_list) > 0
>>> my_list.pop()
'ABC'
>>> assert len(my_list) > 0
Traceback (most recent call last):File "<pyshell#18>", line 1, in <module>assert len(my_list) > 0
AssertionError
AttributeError
尝试访问未知的对象属性。当试图访问的对象属性不存在时抛出的异常。
>>> my_list = []
>>> my_list.huhan
Traceback (most recent call last):File "<pyshell#22>", line 1, in <module>my_list.huhan
AttributeError: 'list' object has no attribute 'huhan'
EOFError
用户输入文件末尾标志EOF(Ctrl+d)
FloatingPointError
浮点计算错误
GeneratorExit
generator.close()方法被调用的时候
ImportError
导入模块失败的时候
IndentationError
缩进错误
IndexError
索引超出序列的范围
>>> my_list = [1, 2, 3]
>>> my_list[3]
Traceback (most recent call last):File "<pyshell#26>", line 1, in <module>my_list[3]
IndexError: list index out of range
KeyError
字典中查找一个不存在的关键字
>>> my_dict = {'one': 'いち', 'two': 'に', 'three': 'さん'}
>>> my_dict['one']
'いち'
>>> my_dict['four']
Traceback (most recent call last):File "<pyshell#33>", line 1, in <module>my_dict['four']
KeyError: 'four'
KeyboardInterrupt
用户输入中断键(Ctrl+c)
MemoryError
内存溢出(可通过删除对象释放内存)
NameError
尝试访问一个不存在的变量
>>> abc
Traceback (most recent call last):File "<pyshell#6>", line 1, in <module>abc
NameError: name 'abc' is not defined
NotImplementedError
尚未实现的方法
OSError
操作系统产生的异常(例如打开一个不存在的文件)
>>> my_file = open('D:\\Python\\test\\no.txt', 'r')
Traceback (most recent call last):File "<pyshell#9>", line 1, in <module>my_file = open('D:\\Python\\test\\no.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\Python\\test\\no.txt'
OverflowError
数值运算超出最大限制
ReferenceError
弱引用(weak reference)试图访问一个已经被垃圾回收机制回收了的对象
RuntimeError
一般的运行时错误
StopIteration
迭代器没有更多的值
SyntaxError
Python的语法错误
>>> print('a')
a
>>> print 'a'
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('a')?
TabError
Tab和空格混合使用
SystemError
Python编译器系统错误
SystemExit
Python编译器进程被关闭
TypeError
不同类型间的无效操作
>>> age = 12
>>> print("I'm " + str(age) +" years old.")
I'm 12 years old.
>>>
>>> print("I'm " + age +" years old.")
Traceback (most recent call last):File "<pyshell#19>", line 1, in <module>print("I'm " + age +" years old.")
TypeError: can only concatenate str (not "int") to str
UnboundLocalError
访问一个未初始化的本地变量(NameError的子类)
UnicodeError
Unicode相关的错误(ValueError的子类)
UnicodeEncodeError
Unicode编码时的错误(UnicodeError的子类)
UnicodeDecodeError
Unicode解码时的错误(UnicodeError的子类)
UnicodeTranslateError
Unicode转换时的错误(UnicodeError的子类)
ValueError
传入无效的参数
ZeroDivisionError
除数为零
>>> 5 / 0
Traceback (most recent call last):File "<pyshell#25>", line 1, in <module>5 / 0
ZeroDivisionError: division by zero
Python异常处理
try 语句
try-except 语句
语句格式:
try:检测范围
except Exception[as reason]:出现异常(Exception)后的处理代码
try 语句检测范围内一旦出现异常,剩下的语句将不会被执行。
例:
f = open('不一定存在的文件.txt')
print(f.read())
f.close()# 文件不存在时报错:
'''
FileNotFoundError: [Errno 2] No such file or directory: '不一定存在的文件.txt'
'''
# 不带参数,知其然不知其所以然~~
try:f = open('不一定存在的文件.txt')print(f.read())f.close()
except OSError: # FileNotFoundError 属 OSErrorprint('文件或路径不存在呀不存在~~~')'''
文件或路径不存在呀不存在~~~
'''
# 带参数,列出错误原因。知其然亦知其所以然~~
try:f = open('不一定存在的文件.txt')print(f.read())f.close()
except OSError as reasonXYZ123_custom: # 可以自定义print('文件或路径不存在呀不存在~~~\n错误的原因是:' + str(reasonXYZ123_custom)) # 需将错误内容强制变为字符串'''
文件或路径不存在呀不存在~~~
错误的原因是:[Errno 2] No such file or directory: '不一定存在的文件.txt'
'''
一个try语句还可以搭配多个except语句,对关注的异常进行处理。
try:sum = 1 + '1' # 发现异常将跳过其他语句f = open('不一定存在的文件.txt')print(f.read())f.close()except OSError as reasonXYZ123:print('文件或路径不存在呀不存在~~~\n错误的原因是:' + str(reasonXYZ123))
except TypeError as reasonXYZ123: #这个错误先发生~print('类型出错啦~~~\n错误的原因是:' + str(reasonXYZ123))'''
类型出错啦~~~
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
'''
对异常进行统一处理:
except后边还可以跟多个异常,然后对这些异常进行统一的处理:
try:sum = 1 + '1' # 错上加错~f = open('不一定存在的文件.txt')print(f.read())f.close()except (TypeError, OSError) as reasonXYZ123: # except后边跟多个异常print('出错啦~~~\n错误的原因是:' + str(reasonXYZ123))'''
出错啦~~~
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
'''
try:sum = 1 + '1'f = open('不一定存在的文件.txt')print(f.read())f.close()except (TypeError, OSError): # 不报Error原因print('出错啦~~~')'''
出错啦~~~
'''
捕获所有异常:
缺点:会隐藏所有未想到并且未做好处理准备的错误。如:Ctrl+C 试图终止程序,却被解释为 KeyboardInterrupt 异常。
try:int('abc') # 错1sum = 1 + '1' # 错2f = open('不一定存在的文件.txt') # 错3print(f.read())f.close()except:print('出错啦!!!')'''
出错啦!!!
'''
try-finally 语句
定义清理行为。如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出。
finally 语句块无论如何都将被执行:
try 语句块没有错误:跳过 except 语句块执行 finally 语句块的内容。
try 语句块出现错误:先执行 except 语句块再执行 finally 语句块的内容。
try:检测范围
except Exception[as reason]:出现异常(Exception)后的处理代码
finally:无论如何都会被执行的代码
例:
try:f = open('D:\\Python\\test\\存在的文件.txt', 'w') # 成功打开print(f.write('写入文件的东西')) # 写入字符串,返回字符长度sum = 1 + '1' # Errorf.close() # 因为Error,跳过关闭操作,数据在缓存,写入未保存至文件except (TypeError, OSError):print('出错啦~~~')'''
7
出错啦~~~
'''
解决上例未保存的问题:
try:f = open('D:\\Python\\test\\存在的文件.txt', 'w')print(f.write('写入文件的东西'))sum = 1 + '1' # Errorexcept (TypeError, OSError):print('出错啦~~~')finally:f.close() # 无论如何都将被执行'''
7
出错啦~~~
'''
raise 语句
使用 raise 语句抛出一个指定的异常。
>>> raise # 单独使用
Traceback (most recent call last):File "<pyshell#0>", line 1, in <module>raise
RuntimeError: No active exception to reraise
>>>
>>> raise ZeroDivisionError # 抛出指定异常
Traceback (most recent call last):File "<pyshell#2>", line 1, in <module>raise ZeroDivisionError
ZeroDivisionError
>>>
>>> raise ZeroDivisionError('除数不能为零~~!') # 加参数,对异常进行解释
Traceback (most recent call last):File "<pyshell#4>", line 1, in <module>raise ZeroDivisionError('除数不能为零~~!')
ZeroDivisionError: 除数不能为零~~!
else 语句
见:《Python:else语句》
with 语句
with 语句可以保证诸如文件之类的对象在使用完之后一定会正确的执行它的清理方法。
with open("myfile.txt") as f:for line in f:print(line, end="")
以上这段代码执行完毕后,就算在处理过程中出问题了,文件 f 总是会关闭。
例:
try:f = open('data.txt', 'w')for each_line in f:print(each_line)except OSError as reason:print('出错啦!' + str(reason))finally:f.close()
使用 with 语句改写:
try:with open('data.txt', 'w') as f: # with关注文件,在没用的时候自动调用f.close()for each_line in f: # 注意缩进print(each_line)except OSError as reason:print('出错啦!' + str(reason))
Python异常及处理相关推荐
- Python培训教程分享:Python异常机制
在学习Python技术的时候,我们经常会遇到一些异常,例如导致程序在运行过程中出现的中断或退出,我们都称之为异常,大多数的异常都不会被程序处理,而是以错误信息的形式展现出来.本期Python培训教 ...
- 一行代码简化Python异常信息:错误清晰指出,排版简洁美观 | 开源分享
鱼羊 发自 凹非寺 量子位 报道 | 公众号 QbitAI 即使是Python,报错时也令人头大. 看着这一堆乱麻,不知道是该怀疑人生,还是怀疑自己手残. 那么,Python异常输出美化工具Prett ...
- python——异常(1),捕获特定异常
python--异常(1),捕获特定异常 参考文章: (1)python--异常(1),捕获特定异常 (2)https://www.cnblogs.com/kekefu/p/12317986.html ...
- python异常之ModuleNotFoundError: No module named ‘test01inner02‘
python异常之ModuleNotFoundError: No module named 'test01inner02' 参考文章: (1)python异常之ModuleNotFoundError: ...
- python 异常处理中try else语句的使用
python 异常处理中try else语句的使用 参考文章: (1)python 异常处理中try else语句的使用 (2)https://www.cnblogs.com/journey-mk5/ ...
- python代码大全表解释-【初学】Python异常代码含义对照表
原标题:[初学]Python异常代码含义对照表 Python常见的异常提示及含义对照表如下: 异常名称 描述 BaseException 所有异常的基类 SystemExit 解释器请求退出 Keyb ...
- python错误-python异常与错误区别
错误和异常概念 错误: 1.语法错误:代码不符合解释器或者编译器语法 2.逻辑错误:不完整或者不合法输入或者计算出现问题 异常:执行过程中出现万体导致程序无法执行 1.程序遇到逻辑或者算法问题 2.运 ...
- Python异常及处理方法总结
原文:https://blog.csdn.net/polyhedronx/article/details/81589196 作者:polyhedronx 调试Python程序时,经常会报出一些异常,异 ...
- python超神之路:python异常对照表
python异常对照表 异常名称 描述 BaseException 所有异常的基类 SystemExit 解释器请求退出 KeyboardInterrupt 用户中断执行(通常是输入^C) Excep ...
- Python异常捕获及自定义异常类
Python异常捕获及自定义异常类 一.什么是异常? 异常是一个与业务逻辑无关的BUG,一个潜在错误或者网络错误事件等,如:尚未实现的函数,缩进错误,Python语法错误等.该事件可能会在程序执行过程 ...
最新文章
- 苹果硬盘容量启动linux,你的MAC OS之旅
- linux 加密库 libsodium 安装
- Redis 数据类型之(底层解析)
- python matplotlab.pyplot.axis()函数的用法
- 父子组建传值_父子组件及兄弟组件传值demo
- python 邮件报警
- MFc消息映射机制理解
- python学习之路day02
- S5PV210 软件实现电阻屏两点触摸
- 3.5W 字详解 Java 集合
- spring集成shiro原理
- pyenv、ipython、jupyter的安装使用
- Callnovo如何因小见大,高端定制——“快乐的音符跳动在异国他乡”篇
- caffe配置 一生不可自决
- 亲历的商务谈判过程(续)——谈谈国企和我的经历
- forward请求转发
- 车内看车头正不正技巧_坡道定点停车和起步技巧详解,助你100%过关
- 分布式 | 拜占庭将军问题
- myEclipse2018下载及安装详细教程
- 拒绝攀比 理性分期消费