Python如何将异常排除在;“一网打尽”;
假设我有:Python如何将异常排除在;“一网打尽”;,python,exception,Python,Exception,假设我有: try: result = call_external_service() if not result == expected: raise MyException() except MyException as ex: # bubble up raise ex except Exception: # unexpected exceptions from calling external service do_some_
try:
result = call_external_service()
if not result == expected:
raise MyException()
except MyException as ex:
# bubble up
raise ex
except Exception:
# unexpected exceptions from calling external service
do_some_logging()
由于我有限的python知识,我想不出一种优雅的方法来冒泡出MyException
异常,我希望我能做如下事情:
try:
result = call_external_service()
if not result == expected:
raise MyException()
except Exception, exclude(MyException):
# unexpected exceptions from calling external service
do_some_logging()
您的问题似乎是在try块中包装了太多的代码。这个怎么样
try:
result = call_external_service()
except Exception:
# unexpected exceptions from calling external service
do_some_logging()
if result != expected:
raise MyException()
如果类型与MyException1匹配,我可能会重新提出它。您的第一个代码有什么问题?2) 为什么你的问题以“让我详细说明一下”开头?“你是在其他地方继续谈话吗?”@NedBatchelder 1)我认为,抓住它并提起它不是很直截了当的阅读方式。2) 我认为标题不够清楚,所以我说了“详细说明”,但我已经更新了它。它确实有意义:)我认为
if result!=预期:
在我的例子中有点过于简化,有时我需要访问结果
元素,而结果
可能不是我想要的类型,我只需要放置更多的try/except块即可。。。