我正在尝试捕获未引发的异常,只是记录了异常。有什么办法吗?
def exampleFunction():
try:
x = 1 / 0
except Exception:
logging.exception('divide by 0 error here.')
try:
exampleFunction()
except <condition based on if logging.exception was called>
print('there was a divide by 0 error when I called exampleFunction()')
答案 0 :(得分:2)
我认为exampleFunction是您不拥有的一些可怕的第三方代码,否则会有很多更好的选择。
您可以做什么:
import logging # make sure this is the FIRST import of logging
import horrible_third_party_lib
def catch_log(msg):
# do something when this is called
old_logging = logging.exception
try:
logging.exception=catch_log
horrible_third_party_lib.exampleFunction()
finally:
logging.exception=old_logging
然后,您可以在函数中执行所需的所有操作。它对导入顺序很可怕而且很敏感,但是我已经使用了它并且可以正常工作(scikit learning做类似的令人讨厌的事情。)
答案 1 :(得分:0)
问题:我正在尝试捕获异常
问题标题应重写为“ 我正尝试提出例外情况”
阅读Manning publishing
似乎有些双重工作,但您可以这样做:
html
输出:
def exampleFunction(): try: x = 1 / 0 except Exception as e: print("logging.exception({})".format(e)) raise try: exampleFunction() except ZeroDivisionError as e: print('there was a divide by 0 error when I called exampleFunction()')
经过Python:3.5.3
的测试