在捕獲異常時,應該盡可能指定特定的異常,而不是只使用 except
語句。
比如說,except
語句會捕獲 KeyboardInterrupt
和 SystemExit
異常,但 KeyboardInterrupt
可能是我們通過 Ctrl + C
主動觸發的,顯然是不希望被捕獲的。
這樣做會影響我們對異常的判斷。
如果實在不知道是什么異常,至少要這樣使用:except Exception
。
再舉一個例子:
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except:
logger.error('An error occurred!')
這樣捕獲異常顯然是不好的,應該采用下面這樣的方式進行優化。
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except User.DoesNotExist:
logger.error('The user does not exist with that ID')
推薦閱讀: