python笔记-异常机制
异常的类型
Python的异常是由类定义的,所有的异常都来自于BaseException类,不同类型的异常都继承自父类BaseException
异常:指在程序运行过程中出现问题而导致无法执行,如程序的逻辑、算法错误,计算机资源不足或IO错误等。
- assertionError 断言失败抛出异常
- AttributeError 当调用的属性或方法不存在时,抛出异常
- IndexEror 当使用的索引值超过序列的总长度 抛出异常
- KeyError 当通过key访问字典,查找的key不存在时,抛出异常
- NameError 当调用一个不存在的的变量时,抛出此异常
- OSError 操作系统产生异常,如访问一个不存在的文件,会抛出OSError的子类FileNotFound异常
- SyntaxError 语法错误
- TypeError 不同数据类型的无效操作
- ZeroDivisionError 除数为0 时,抛出此异常
- IndentationError 缩进异常
捕捉异常
处理异常的语法由4个关键字:
try : 检测代码是否出现异常
except :捕捉异常信息并对异常进行处理
else:如果关键字 try 下的代码没有问题,就执行当前代码块
finally:无论是否出现异常,都要执行
示例:
if __name__=="__main__":
try:
s=Student('a')
pass
except NameError as err:
print("this is a nameError : ",err)
except Exception as e:
print("发生了一些错误:",e)
finally:
print("The code here must be excuted,regardless of wether there is an error!!! ")
输出:
this is a nameError: name 'Student' is not defined
The code here must be excuted,regardless of wether there is an error!!!
在一个异常机制中,可以有多个except 来捕获不同的异常,并处理
执行顺序是从上往下
异常机制同样可以进行嵌套,就是当捕获一个异常后进行相应处理,再try进行异常的捕获并处理
if __name__=="__main__":
try:
s=Student('a')
pass
# except NameError as err:
# print("this is a nameError:",err)
except Exception as e:
print("发生了一些错误:",e)
try:
s=Student('b')
except NameError as e:
print("this is mysecond show!")
finally:
print("The code here must be excuted,regardless of wether there is an error!!! ")
输出
发生了一些错误: name 'Student' is not defined
this is mysecond show!
The code here must be excuted,regardless of wether there is an error!!!
自定义异常
使用 raise 关键字,关键字后填写异常的类型及异常信息
if __name__=='__main__':
try:
raise NameError("哈哈哈,this is error")
except Exception as e:
print("this is Exception.",e)
输出
this is Exception. 哈哈哈,this is error
自定义异常类
在抛出捕获异常时,如果想使用自定义的异常,可以通过自定义异常类,只要这个类继承自 Exception 类即可
class myError(Exception):
pass
try:
raise myError("this is a customize exception!")
except myError as err:
print("i catch one erro here. ",err)
输出:
I catch one erro here. this is a customize exception!
异常的追踪
为了能够精准找出代码的问题所在,Python的标准库提供了traceback模块,它能精准定位代码的异常信息
导入traceback模块
调用 print_exc() 方法
import traceback
if __name__=='__main__':
class myError(Exception):
pass
try:
raise myError("this is a customize exception!")
except myError as err:
print("i catch one erro here. ",err)
traceback.print_exc()
输出:
i catch one erro here. this is a customize exception!
Traceback (most recent call last):
File "d:/TestFile/CodePractice/ReptilePractice-12/1221_customizeException.py", line 11, in <module>
raise myError("this is a customize exception!")
myError: this is a customize exception!
traceback模块常用方法
traceback模块提供很多的方法,常用的方法有:
print_exception()
输出异常的详细信息,类型、信息、对象、等等
语法:
print_exception(etype,value ,tb ,limit,file,chain)
必选参数:
etype:异常对象的数据类型
value : 代表异常的信息内容
tb : 代表 traceback 的对象信息
一般情况必选参数etype、value和tb可由sys模块的exc_info()方法获取
可选参数:
limit :代表限制异常的追踪层数
file: 要写入异常的文件对象
chain :是否显示异常的__cause__或__content__属性等信息
import traceback
import sys
if __name__=='__main__':
class myError(Exception):
pass
try:
raise myError("this is a customize exception!")
except myError as err:
print("i catch one erro here. ",err)
etype,value,tb=sys.exc_info()
traceback.print_exception(etype,value,tb)
输出
i catch one erro here. this is a customize exception!
Traceback (most recent call last):
File "d:/TestFile/CodePractice/ReptilePractice-12/1221_customizeException.py", line 9, in <module>
raise myError("this is a customize exception!")
myError: this is a customize exception!
print_tb()
输出traceback对象
语法:
print_tb(tb ,[ limit, [ file]])
示例:
import traceback
import sys
if __name__=='__main__':
class myError(Exception):
pass
try:
raise myError("this is a customize exception!")
except myError as err:
print("i catch one erro here. ")
etype,value,tb=sys.exc_info()
traceback.print_tb(tb)
输出
i catch one erro here.
File "d:/TestFile/CodePractice/ReptilePractice-12/1221_customizeException.py", line 9, in <module>
raise myError("this is a customize exception!")
print_exc()
是 print_exception()的简化版,由于etype、value和tb都可以通过sys.exc_info()获取,因此print_exc()自动执行exc_info()来获取这3个参数
语法
print_exc([limit, [file, [chain]]])
示例
import traceback
import sys
if __name__=='__main__':
class myError(Exception):
pass
try:
raise myError("this is a customize exception!")
except myError as err:
print("i catch one erro here. ")
traceback.print_exc()
输出
i catch one erro here.
Traceback (most recent call last):
File "d:/TestFile/CodePractice/ReptilePractice-12/1221_customizeException.py", line 9, in <module>
raise myError("this is a customize exception!")
myError: this is a customize exception!