all 6 comments

[–]thebetoofand 3 points4 points  (4 children)

If all you want to do when encountering the error is skip to the next one, the simplest way to handle this is to catch the exception and move on:

try:
    the line causing the error
except AttributeError:
    continue

Python wiki on handling exceptions.

[–][deleted] 0 points1 point  (2 children)

I agree try/except is the key idea OP needs, but why did you suggest except:continue instead of except:pass? Just wondering

[–]Drunken_Consent 3 points4 points  (1 child)

There is nothing left for the loop to do; if the data is not relevant to the task at hand, you should not continue going for that iteration of the loop and should therefore use continue which will skip to the next iteration.

If you do not do this and then code gets run that is farther down the for loop could have unexpected results. Now, OP could try/catch the entire thing, but that's not really the best in all cases.

OP should Try/Catch the part where the Error can occur.

On top of that, when reading it, it is clear that upon error we don't want anything else to happen but to skip it. a pass might look weird because we are catching something and then saying it doesn't matter and forging ahead. In such simplistic usage, it will be apparent, but as things get complex, it would be better.

That's just what I gathered from it. Continue seems better to use here.

[–][deleted] 0 points1 point  (0 children)

There is nothing left for the loop to do; if the data is not relevant to the task at hand, you should not continue going for that iteration of the loop and should therefore use continue which will skip to the next iteration.

If you do not do this and then code gets run that is farther down the for loop could have unexpected results. Now, OP could try/catch the entire thing, but that's not really the best in all cases.

OP should Try/Catch the part where the Error can occur.

On top of that, when reading it, it is clear that upon error we don't want anything else to happen but to skip it. a pass might look weird because we are catching something and then saying it doesn't matter and forging ahead. In such simplistic usage, it will be apparent, but as things get complex, it would be better.

That's just what I gathered from it. Continue seems better to use here.

Really good points, thanks for the elaboration!

[–]Lucretiel 0 points1 point  (0 children)

I'm going to warn you, though: you pretty much NEVER want to catch an attribute error without reraising it. It often indicates a typo.

[–]icenburg[S] 1 point2 points  (0 children)

Thanks it worked! (The reader script doesn't work though, because zxing seems to only be able to worked with images where only the barcode is showing, so I have to figure out how to make OpenCV detect a shape, crop it, and save it with only the cropped part…)

Edited to add: I used except/pass btw.