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

Updated on: 17-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements