I have the following code
list = [2,5,7,8,'$',1,6]
try:
for i in list:
print(i+1)
except:
print('error')
The output is
3
6
8
9
error
But I want it to print the 'error' and then keep on going with the iteration so that the output would be
3
6
8
9
error
2
7
How do I do that?
This code should work:
for i in list:
try:
print(i+1)
except TypeError:
print(error)
Putting the try-except block inside the loop allows the loop to continue once the error is found. It's also better to specify the error you are catching in case another one pops up that you are not aware of.