Get around raising IndexError


My code is as follows :

for p in qs:
    set = None
        set =
    except IndexError:

    if set:

Problem is that when set is none it still throws IndexError from this part of django.db.models.query:

    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 ?

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:

    [code that might raise an exception]
except Error:
    [code that handles the exception]
    [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.

3/19/2011 5:23:47 PM

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