How to handle exception inside a Python for loop?

PythonProgramming

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
raja
Published on 20-Apr-2018 10:21:16
Advertisements