python 中发生错误时处理异常

Handling exception if error occurs in python

我在尝试解析 JSON 字符串时收到一些记录的错误,我无法处理异常,因此如果在解析 JSON 字符串时发生错误则跳过该记录并移动到下一条记录。

这是代码片段。

ID=[]
json_string=[]
for row in cursor.fetchall():
 ID.append(row[0]) 
 json_string.append(row[1])
address_fields = {
'intersection': [],        
'political': [],        
'country': [], 
}
dumpData = json.dumps(json_string)
json_all = json.loads(dumpData)

id_index = 0
for json_str in json_all:
     address_fields = {
      'intersection': [],        
      'political': [],        
      'country': [], 
      }
     try:
      json_results = json.loads(json_str)
     except IndexError:
      continue


     if isinstance(json_results,dict):
         first_address_components = json_results['results'][0]['address_components']
     else:
         first_address_components = json_results[0]['address_components']
     for item in first_address_components:
         for field_key in address_fields.keys():
            if field_key in item['types']:
               address_fields[field_key].append(item['long_name'])

我首先从 sql table 获取数据并存储 JSON_string 及其 ID,然后尝试解析 JSON 字符串并更新 sql table,因此对于那些出现错误的 JSON 字符串,我想跳过该行并移至下一条记录。 但这还没有完成。尽管如此,我还是无法处理异常。 在这方面的任何帮助都会有所帮助。

谢谢。

而不是这个

try:
  json_results = json.loads(json_str)
except IndexError:
  continue

这样做。

try:
    json_results = json.loads(json_str)
except:
     pass