Dan
Dan

Reputation: 131

Error causing elements of a list when looping / iterating in Python script

I am running a script in a loop for each element of a list. If some elements cause an error, how to print a list of error-causing elements in the end after all the elements are looped through?

For example:

f=["ABC","PQR","UVW","XYZ"]

for f in f:
  try:
    'blah blah'
  except:
    continue 

# print("Error causing elements are " .......... 

Upvotes: 0

Views: 624

Answers (3)

Helpmycator_Coder
Helpmycator_Coder

Reputation: 1

Try this!

try:  
    'your code'
except Exception as e: 
    print(f'The error was " {e} "')
else:
    print("No errors")

Tell me that if this works!

Upvotes: 0

moriarty
moriarty

Reputation: 41

Matin's answer is good. However if you have a list containing the same element multiple times you might want to use a set instead to keep your error message shorter:

f=["ABC","PQR","UVW","XYZ"]
errors=set()

for f in f:
  try:
    'blah blah'
  except:
    errors.add(f)
    continue 

# print(f"Error causing elements are {errors}" .......... 

Upvotes: 0

Matin Zivdar
Matin Zivdar

Reputation: 711

Before getting started

I changed variable f in the for each loop to element for not getting confused and also I wrote a foo function that throws an exception randomly.

Solution

You can add the error-causing elements to a list in the main loop like this: (you have access to the error-causing element in the except: block by variable element in each loop)


f=["ABC","PQR","UVW","XYZ"]
error_elements = []

def foo(element):
    from random import randint
    if randint(0, 1) > 0:
        raise Exception()

for element in f:
    try:
        foo(element)
    except:
        error_elements.append(element)

print("Error causing elements are ", error_elements)

Another Option

Or if you throw the exception, there's another option that you can use and pass the error-causing element and anything else to the Exception function call and access them in except block by catching the Exception like except Exception as e


f=["ABC","PQR","UVW","XYZ"]
error_elements = []

def foo(element):
    from random import randint
    if randint(0, 1) > 0:
        raise Exception('blah blah', element)

for element in f:
    try:
        foo(element)
    except Exception as e:
        # print('Error message is:', e.args[0])
        error_elements.append(e.args[1])

print("Error causing elements are ", error_elements)

Upvotes: 3

Related Questions