Dean
Dean

Reputation: 8978

Continually catch exception in python

I need to keep catching an exception while indexing a list throws a IndexError exception, for example:

l = []
while((l[3]) throws IndexError):
    //Add more data to the list
    l += [3]

How can I keep checking to see if the method call has thrown an exception without having nested a nested try/catch block?

Upvotes: 2

Views: 90

Answers (1)

skamsie
skamsie

Reputation: 2726

It depends what you would like to extend your list with. Assuming 'None' you could do it like this:

l = []
while True:
  try:
    l[3] = 'item'
    break
  except IndexError:
    l.extend([None])

print l # [None, None, None, 'item']

Upvotes: 4

Related Questions