Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to handle a python exception within a loop?

I have a code using 'for loop' that throws an exception. 

a=[]
foo = 'redbullz'
for i in foo:
a.append(i)
print a[8]

How do I catch this exception in the loop in above code?


1 Answer
Rajendra Dharmkar

We can the exception in the code by rewriting it as follows

a=[]
foo = 'redbullz'
try:
for i in foo:
a.append(i)
print a[8]
except Exception as e:
print e

We get following output

list index out of range
Process finished with exit code 0



Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.