Stop raising an IndexError

My code is as follows:

for p in qs: set = None try: set = p.property.property_locations.all() except IndexError: pass if set: 

The problem is that when set is none, it still throws an 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 the system from throwing this error and moving on to the next for for element?

+8
python list django exception
source share
1 answer

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

  • set is built-in (as you can see from the syntax highlighting SO), therefore, by pointing your variable to this name, you obscure the built-in system for no purpose, which is at least a bad practical experience, and can cause problems later in the code.
  • The canonical way to check if set is not None is to write: if set is not None

Even better, the canonical way to write this piece of code is:

 try: [code that might raise an exception] except Error: [code that handles the exception] else: [code that executes when no exception was raised] 

(of course, replace the error for the actual exception)

Thus, you do not even need to check the 'set' at this point.

+14
source share

All Articles