0

I am using a method that raises a KeyError. I would like to run that through a for loop and then display all these errors together at once when it's done with the loop. Is that possible ?

I am doing a Try except as this post indicates in order to ignore the KeyError(s).

bad_list = []
for i in range (10):
   try:
      bad_list.append(checkermethod(i)) #checker method raises TypeError when called
   except KeyError:
      continue
    
if bad_list:
   raise KeyError('\n'.join(bad_list))

I am trying to catch these errors by appending a list, but it's always empty, so it's not really appending anything. This makes sense since I am actually ignoring the errors, but is there any idea on how to do that in another way?

anxiousPI
  • 183
  • 1
  • 12
  • Your method `checkermethod()` does not depend on counter `i`. You call it 10 times and 10 times it fails which means there is no result returned. So what is your `bad_list` supposed to contain, exactly? Exceptions, indexes, or something else? – jurez Jun 22 '21 at 16:38
  • In this case, It's just a dummy method that returns a KeyError. but i will update it with a variable of i so its more clear. – anxiousPI Jun 22 '21 at 16:41
  • It's still not clear what you are trying to do. – jurez Jun 22 '21 at 16:43
  • I am trying to display the errors together instead of the loop breaking after the first keyerror – anxiousPI Jun 22 '21 at 17:09

1 Answers1

1

I found the solution:

bad_list = []
for i in range (10):
   try:
      checkermethod(i) #checker method raises TypeError when called
   except KeyError as e:
      bad_list.append(e.args[0])
    
if bad_list:
   raise KeyError('\n'.join(bad_list))
anxiousPI
  • 183
  • 1
  • 12