Catch error in a for loop python

后端 未结 3 488
既然无缘
既然无缘 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: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.

提交回复
热议问题