Get around raising IndexError
My code is as fol开发者_运维问答lows :
for p in qs:
set = None
try:
set = p.property.property_locations.all()
except IndexError:
pass
if set:
Problem is that when set is none it still throws IndexError from this part of django.db.models.query:
try:
qs = self._clone()
qs.query.set_limits(k, k + 1)
return list(qs)[0]
except self.model.DoesNotExist, e:
raise IndexError(e.args)
How to stop system from throwing this error and continuing to next element in for loop ?
In any case, there are two mistakes in your code:
- set is a builtin (as you can see from SO's syntax highlighting), so by giving your variable that name you're shadowing the builtin for no purpose, which is at least bad practice, and likely to cause issues later in the code.
- The canonical way to check if set is not None is by writing: if set is not None
Better yet, the canonical way to write that code snippet is:
try:
[code that might raise an exception]
except Error:
[code that handles the exception]
else:
[code that executes when no exception was raised]
(substitute Error for the actual exception, of course)
That way you don't even have to check 'set' at that point.
精彩评论