在捕获异常时,应该尽可能指定特定的异常,而不是只使用 except
语句。
比如说, except
语句会捕获 KeyboardInterrupt
和 SystemExit
异常,但 KeyboardInterrupt
可能是我们通过 Ctrl + C
主动触发的,显然是不希望被捕获的。
这将影响我们对异常情况的判断。
[En]
This will affect our judgment of anomalies.
如果实在不知道是什么异常,至少要这样使用: except Exception
。
再举一个例子:
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except:
logger.error('An error occurred!')
以这种方式捕获异常显然不好,应该按以下方式进行优化。
[En]
It is obviously not good to catch exceptions in this way and should be optimized in the following way.
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')
推荐阅读:
- 计算机经典书籍
- 技术博客 : 硬核后端开发技术干货,内容包括 Python、Django、Docker、Go、Redis、ElasticSearch、Kafka、Linux 等。
- Go 程序员 : Go 学习路线图,包括基础专栏,进阶专栏,源码阅读,实战开发,面试刷题,必读书单等一系列资源。
- 面试题汇总 : 包括 Python、Go、Redis、MySQL、Kafka、数据结构、算法、编程、网络等各种常考题。
Original: https://www.cnblogs.com/alwaysbeta/p/15978608.html
Author: yongxinz
Title: python 编辑器提示 do not use bare except
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/509862/
转载文章受原作者版权保护。转载请注明原作者出处!