![](/img/trans.png)
[英]Between raise Error and logging the Error, which one is a better practice in Python?
[英]Better to raise an error directly or from within a logger
以下哪两种引发错误的方法是首选?
def _fetch_data(self):
if self.from_cache:
logger.debug('Trying to load local file %s...' % self.fp)
# Grab the data from a local file
if not os.path.exists(self.fp):
# first way -- from logger
logger.error('ERROR: Local file {self.fp} does not exist')
# second way -- directly raising
raise SystemExit(f"ERROR: Local file {self.fp} does not exist")
为什么一种方法优于另一种方法?
其中一个打印并且不采取任何行动(暗示问题不是致命的),另一个实际上尝试终止程序(尽管在这种情况下惯用的方法只是sys.exit(f"ERROR: Local file {self.fp} does not exist")
;它等同于raise
,但在意图上稍微清晰一些)。
选择一个在上下文中有意义的; 如果文件是继续操作所必需的,则引发异常(如果您愿意,请先记录),如果继续操作的合理方式不是致命的,您可以只记录。
请注意SystemExit
意味着它真的很致命(人们通常不应该试图抓住它)。 通常,如果调用者知道处理问题的好方法,最好提出其他一些更具描述性、更少“暗示绝对致命”的异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.