python的Exception处理中使用到的概念
参考资料:Python中获取异常(Exception)信息
1.try except xxxException as e
2.raise
3.traceback
4.sys.exc_info()
import sys
import traceback
print('########################################################')
print("1/0 Exception Info")
print('---------------------------------------------------------')
try:
1/0
except Exception as e:
print('str(Exception):\t', str(Exception))
print('str(e):\t\t', str(e))
print('repr(e):\t', repr(e))
# Get information about the exception that is currently being handled
exc_type, exc_value, exc_traceback = sys.exc_info()
print('e.message:\t', exc_value)
print("Note, object e and exc of Class %s is %s the same." %
(type(exc_value), ('not', '')[exc_value is e]))
print('traceback.print_exc(): ', traceback.print_exc())
print('traceback.format_exc():\n%s' % traceback.format_exc())
print('e.message:\t', exc_value)
print('exc_value.type:\t', type(exc_value))
print('repr(e):\t', repr(e))
print('str(e):\t\t', str(e))
# sys.exc_info()获取的exc_value 和 e 的关系
print("Note, object e and exc of Class %s is %s the same." %
(type(exc_value), ('not', '')[exc_value is e]))
print('########################################################')
代码比较杂,需要明确sys.exc_info() 方法可以获取正在处理的异常信息,即 except 子句正在处理的异常,其返回值为一个tuple类型的三元组(exc_type, exc_value, exc_traceback),其中,exc_type为获取到的异常类型;exc_value为该异常类型对象;exc_traceback为一个 traceback 对象,包含异常最初发生的调用栈信息。
exc_value 和 接收的 xxxException as e的 e等价,以下两者只写一种,但是两者等价,效果一致
A.print(‘str(e):\t\t’, str(e)) 输出报错的说明
B.print(‘repr(e):\t’, repr(e)) 错误类型和报错说明,特异化了repr
C.print(‘exc_value.type:\t’, type(exc_value)) 错误类型
D. e.message str(e) exc_value的直接输出,都是报错的说明
E.print(‘traceback.format_exc():\n%s’ % traceback.format_exc()) 详细的错误输出,包含报错位置
总结下,根据需要输出错误提示,错误是用来查bug和保持代码稳定性的,如果是爬虫,使用错误处理保证程序不会因为各种原因中断,这个时候的错误处理需要记录错误的原因和如何根据记录下的内容,重新爬取,平常的编程,对于多个可能产生错误的地方,我们需要知道是哪个地方发生了什么错误,或者某些时候要主动抛出错误
自定义错误
class Wrongstr_Exceptin(Exception):
def __init__(self,str):
self.str = str
def __str__(self):
print(str)
if len(sql_list) != 1:
raise Wrongstr_Exceptin('错误' + 'XXXXX:' + position_xian)
使用raise主动抛出错误,使用raise后需要主动接收错误,不然程序就终止了
try:
check_list = select_by_type(backstage, position_list)
except Wrongstr_Exceptin as wrongstr:
print(wrongstr.str)
return [wrongstr.str,'','']
# input_str = input("出现错误,输入任意键退出")
# sys.exit()
return check_list
这里的wrongstr.str str(wrongstr) 就是上面的输出错误的各类写法,输出的就是上面的’错误’ + ‘XXXXX:’ + position_xian的错误