mou*_*one 8 python django exception list
我的代码如下:
for p in qs:
set = None
try:
set = p.property.property_locations.all()
except IndexError:
pass
if set:
Run Code Online (Sandbox Code Playgroud)
问题是当set为none时,它仍会从django.db.models.query的这一部分抛出IndexError:
try:
qs = self._clone()
qs.query.set_limits(k, k + 1)
return list(qs)[0]
except self.model.DoesNotExist, e:
raise IndexError(e.args)
Run Code Online (Sandbox Code Playgroud)
如何阻止系统抛出此错误并继续执行for循环中的下一个元素?
小智 14
无论如何,您的代码中存在两个错误:
更好的是,编写该代码片段的规范方法是:
try:
[code that might raise an exception]
except Error:
[code that handles the exception]
else:
[code that executes when no exception was raised]
Run Code Online (Sandbox Code Playgroud)
(当然,替换实际异常的错误)
这样你甚至不必在那时检查'设置'.
| 归档时间: |
|
| 查看次数: |
26051 次 |
| 最近记录: |