![](/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.