My code is as follows :
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 ?
“List index out of range” error occurs in Python when we try to access an undefined element from the list. The only way to avoid this error is to mention the indexes of list elements properly.
The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.
You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.
The IndexError exception in Python means that you are trying to access an index that doesn't exist. For example you are trying to access the 5th index of a list, but there are only 4 elements present. It is part of the LookupError Exception class.
In any case, there are two mistakes in your code:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With