Reputation: 19
I am trying to loop the object check which is a specific database obtained from the OpenLCA software. This database has a certain bug in some instance of it. Whenever I am running the for statement, after looping through many instances, when the code encounters buggy instance it throws me a error in the for loop condition -
for i in check:
How do I enforce exception handling on the for loop condition statement as shown. Please help.
Just to be very specific - the error is not thrown for the statement inside the loop. Its thrown in for i in check
statement itself. So having try inside the loop does not help me for this case.
check = client.get_all(olca.Process)
for i in check:
#print(type(i))
process = i.default_allocation_method
name = i.name
print(name)
File "U:/Desktop/Box/Box Sync/Research_compile/electricitylci/pythonapiopenlca.py", line 101, in for i in check:
File "C:\ProgramData\Anaconda3\lib\site-packages\olca\ipc.py", line 105, in get_all e.from_json(r)
File "C:\ProgramData\Anaconda3\lib\site-packages\olca\schema.py", line 1882, in from_json self.default_allocation_method = AllocationType(val)
File "C:\ProgramData\Anaconda3\lib\enum.py", line 291, in call return cls.new(cls, value)
File "C:\ProgramData\Anaconda3\lib\enum.py", line 533, in new return cls.missing(value)
File "C:\ProgramData\Anaconda3\lib\enum.py", line 546, in missing raise ValueError("%r is not a valid %s" % (value, cls.name))
ValueError: 'NO_ALLOCATION' is not a valid AllocationType
Upvotes: 0
Views: 101
Reputation: 3620
use try
and except
inside your for
loop like this:
for i in check:
try:
process = i.default_allocation_method
name = i.name
print(name)
except Exception as e:
print("error is: {}".format(e))
UPDATE: If your error raised in for
loop statement and you want to continue your for loop execution even after error was raise, you can replace it with while
loop (if check
has len
and is not an iterator) and handle exceptions like this:
check = client.get_all(olca.Process)
i = 0
while i < len(check): # or other function that returns length of check
try:
process = check[i].default_allocation_method
name = check[i].name
print(name)
except Exception as e:
print("error is: {}".format(e))
finally:
i += 1
if check
is an iterator you can use generator function (see @tripleee answer)
Upvotes: 2
Reputation: 189938
There isn't really a way to isolate a try
to only cover the for
statement. Perhaps wrap it something like this:
def wrap_next(getter):
while True:
try:
yield getter.next()
except ValueError:
howl(misery, desperation)
for i in wrap_next(check)
... Do things
Upvotes: 4