Get around raising IndexError


Question

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 ?

1
8
3/2/2011 11:34:30 AM

In any case, there are two mistakes in your code:

  1. 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.
  2. 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.

14
3/19/2011 5:23:47 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon