我想处理AssertionError
s以隐藏用户不必要的堆栈跟踪部分,并打印一条消息,说明错误发生的原因以及用户应对此做些什么。
有没有办法找出assert
在except
区块内失败的哪条线或陈述?
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
print 'Houston, we have a problem.'
print
print 'An error occurred on line ???? in statement ???'
exit(1)
我不想将其添加到每个断言语句中:
assert 7 == 7, "7 == 7"
因为它重复信息。
使用traceback模块:
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
print('An error occurred on line {} in statement {}'.format(line, text))
exit(1)
跟踪模块和sys.exc_info对于跟踪异常源是过度的。这都是默认的追溯。所以不要再调用exit(1)重新加注:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
这给出了以下输出,包括违规语句和行号:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
类似地,日志记录模块可以轻松记录任何异常(包括捕获且永不重新引发的异常)的回溯:
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)