Catch error in a for loop python

后端 未结 3 487
既然无缘
既然无缘 2021-01-20 11:00

I have a for loop on an avro data reader object

for i in reader:
    print i

then I got a unicode decode error in the for statement so I wa

相关标签:
3条回答
  • 2021-01-20 11:32

    If your error is in for i in. Then try this, it will skip element in iterator if UnicodeDecodeError occurs.

    iterobject = iter(reader)
    while iterobject:
        try:
            print(next(iterobject))
        except StopIteration:
            break
        except UnicodeDecodeError:
            pass
    
    0 讨论(0)
  • 2021-01-20 11:32

    You need the try/except inside the loop:

        for i in reader:
           try: 
               print i
           except UnicodeEncodeError:
               pass
    

    By the way it's good practice to specify the specific type of error you're trying to catch (like I did with except UnicodeEncodeError:, since otherwise you risk making your code very hard to debug!

    0 讨论(0)
  • 2021-01-20 11:45

    You can except the specific error, and avoid unknown errors to pass unnoticed.

    Python 3.x:

    try:
        for i in reader:
            print i
    except UnicodeDecodeError as ue:
        print(str(ue))
    

    Python 2.x:

    try:
        for i in reader:
            print i
    except UnicodeDecodeError, ue:
        print(str(ue))
    

    By printing the error it's possible to know what happened. When you use only except, you except anything (And that can include an obscure RuntimeError), and you'll never know what happened. It can be useful sometimes, but it's dangerous and generally a bad practice.

    0 讨论(0)
提交回复
热议问题