python 编辑器提示 do not use bare except

简介: python 编辑器提示 do not use bare except

在捕获异常时,应该尽可能指定特定的异常,而不是只使用 except 语句。


比如说,except 语句会捕获 KeyboardInterruptSystemExit 异常,但 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')


目录
相关文章
|
2月前
|
Python
|
5月前
|
数据采集 数据挖掘 程序员
2024年Python最全资深程序员:学Python我推荐你用这几款编辑器,2024年最新面试考哪些
2024年Python最全资深程序员:学Python我推荐你用这几款编辑器,2024年最新面试考哪些
2024年Python最全资深程序员:学Python我推荐你用这几款编辑器,2024年最新面试考哪些
|
2月前
|
Python
Python 中的 try 和 except 块
【8月更文挑战第29天】
24 6
|
2月前
|
前端开发 Python
60行Python代码开发在线markdown编辑器
60行Python代码开发在线markdown编辑器
|
2月前
|
Python
python 升级后 yum 无法使用 File "/usr/bin/yum", line 30 except KeyboardInterrupt, e: `/usr/libexec/urlgrabber-ext-down`
python 升级后 yum 无法使用 File "/usr/bin/yum", line 30 except KeyboardInterrupt, e: `/usr/libexec/urlgrabber-ext-down`
14 0
|
3月前
|
自然语言处理 Python
【Python】已解决:Resource punkt not found. Please use the NLTK Downloader to obtain the resource:
【Python】已解决:Resource punkt not found. Please use the NLTK Downloader to obtain the resource:
191 1
|
4月前
|
开发者 Python
在Python中,异常处理通过`try`、`except`、`else`和`finally`关键字进行
【6月更文挑战第26天】在Python中,异常处理通过`try`、`except`、`else`和`finally`关键字进行。基本结构包括尝试执行可能抛出异常的代码,然后指定`except`来捕获特定或任何类型的异常。`else`块在`try`无异常时执行,`finally`块确保无论是否发生异常都会执行,例如用于清理。可以使用`raise`重新抛出异常,而自定义异常则允许创建特定的错误类。这种机制增强了代码的健壮性。
56 7
|
4月前
|
定位技术 Python
Python的try、except异常处理模块使用方法
所以,我们就解决了由于可能具有的arcpy.ExecuteError异常而导致的程序中断问题;大家在实际使用时,按照自己程序中可能出现的报错类,对本文出现的arcpy.ExecuteError异常类加以修改即可。
|
3月前
|
自然语言处理 Java 开发工具
【Python】已解决Resource averaged_perceptron_tagger not found. Please use the NLTK Downloader to obtain t
【Python】已解决Resource averaged_perceptron_tagger not found. Please use the NLTK Downloader to obtain t
85 0
|
3月前
|
自然语言处理 Python
【Python】已解决:Resource stopwords not found. Please use the NLTK Downloader to obtain the resource:
【Python】已解决:Resource stopwords not found. Please use the NLTK Downloader to obtain the resource:
87 0
下一篇
无影云桌面