避免引发IndexError
我的代码如下:
for p in qs:
set = None
try:
set = p.property.property_locations.all()
except IndexError:
pass
if 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)
怎么才能让系统不再抛出这个错误,而是继续处理for循环中的下一个元素呢?
1 个回答
13
无论如何,你的代码里有两个错误:
- “set”是一个内置的东西(你可以从StackOverflow的语法高亮看到),所以如果你把你的变量命名为“set”,就会把这个内置的东西给覆盖掉,这样做不仅不太好,而且可能会在后面的代码中引发问题。
- 检查“set”是否不为None的标准写法是:if set is not None
更好的写法是这样的:
try:
[code that might raise an exception]
except Error:
[code that handles the exception]
else:
[code that executes when no exception was raised]
(当然,记得把“Error”替换成实际的异常类型)
这样你在那时候就不需要再检查“set”了。