发生异常后如何继续?蟒蛇 [英] How to continue after an exception? Python

查看:74
本文介绍了发生异常后如何继续?蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环,用于解析从Yelp中提取的数据。有时候,由于某些公司名称,我会遇到以下异常情况: ascii编解码器无法在位置3处编码字符u \xf1:序数不在范围内(128)。由于这很普遍,因此我希望我的for循环在此异常之后跳过引发异常的行继续迭代。最好的方法是什么?出于某些原因,对我来说,使用continue无效。

I have a for loop that's parsing data being pulled from Yelp. Sometimes, I get the following exception due to some of the business names:'ascii' codec can't encode character u'\xf1' in position 3: ordinal not in range(128). Since this is pretty common, I would like my for loop to continue iterating after this exception skipping the line that's throwing the exception. What would be the best way? For some reason using continue doesn't work for me.

try:
    response = json.loads(conn.read())
    yelp_data =[x for x in response['businesses']]
    logger.info('Connection to yelp was made')
    data_len = len(yelp_data)
    while data_len > 0:
        for line in yelp_data:
            address = [x.encode('UTF8') for x in line['location']['display_address']]
            cat =[','.join([str(c) for c in lst]) for lst in line['categories']]
            Category =','.join(cat)
            target.submit( 'Name = {},Rating = {},URL = {},Review_Count = {},Phone = {},Yelp_ID = {},Address = {}, Category = {}\n'.format(line.get('name'),line.get('rating'),line.get('mobile_url'),line.get('review_count'),line.get('phone'),line.get('id'),", ".join(address), Category),sourcetype=sourcetype)
            data_len = data_len -1

except Exception as e:
    logger.error(e)


推荐答案

您可以尝试在try循环内移动try / except

You can try to move the try/except inside the while loop

while data_len > 0:
    try:
        for line in yelp_data:
            address = [x.encode('UTF8') for x in line['location']['display_address']]
            cat =[','.join([str(c) for c in lst]) for lst in line['categories']]
            Category =','.join(cat)
            target.submit( 'Name = {},Rating = {},URL = {},Review_Count = {},Phone = {},Yelp_ID = {},Address = {}, Category = {}\n'.format(line.get('name'),line.get('rating'),line.get('mobile_url'),line.get('review_count'),line.get('phone'),line.get('id'),", ".join(address), Category),sourcetype=sourcetype)
            data_len = data_len -1

    except Exception as e:
        logger.error(e)

这篇关于发生异常后如何继续?蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆