Computer >> Computer tutorials >  >> Programming >> Python

How to handle exception inside a Python for loop?


You can handle exception inside a Python for loop just like you would in a normal code block. This doesn't cause any issues. For example,

for i in range(5):
   try:
      if i % 2 == 0:
         raise ValueError("some error")
      print(i)
except ValueError as e:
   print(e)

This will give the output

some error
1
some error
3
some error