Python中Try/Except无法捕获pycountry_convert特定异常问题
解决pycountry_convert异常捕获失效问题
你的代码异常捕获逻辑失效的核心原因是:异常变量e是Exception对象,不是字符串,直接用e == "Invalid Country Alpha-2 code: 'TL'"进行比较永远不成立,导致无法触发东帝汶的特殊处理分支,只能返回'N/A'。
方案一:提前判断国家代码(推荐)
在调用大陆转换函数前,先检查东帝汶的Alpha-2代码'TL',直接返回对应的大陆编码'AS',无需触发异常,代码更高效清晰:
import pycountry_convert as pc def pegacontinente(nomepais): nomepais = nomepais.replace("-", " ") ignore_words = ['and', 'the'] nomepais = ' '.join([word.capitalize() if word not in ignore_words else word for word in nomepais.split()]) try: country_code = pc.country_name_to_country_alpha2(nomepais, cn_name_format="default") # 提前处理东帝汶的特殊情况 if country_code == 'TL': return 'AS' return pc.country_alpha2_to_continent_code(country_code) except Exception: return 'N/A'
方案二:正确匹配异常字符串
如果必须通过异常捕获处理,需要将Exception对象转换为字符串后再进行匹配:
import pycountry_convert as pc def pegacontinente(nomepais): nomepais = nomepais.replace("-", " ") ignore_words = ['and', 'the'] nomepais = ' '.join([word.capitalize() if word not in ignore_words else word for word in nomepais.split()]) try: country_code = pc.country_name_to_country_alpha2(nomepais, cn_name_format="default") continent_name = pc.country_alpha2_to_continent_code(country_code) except Exception as e: # 将异常对象转为字符串后匹配 if str(e) == "Invalid Country Alpha-2 code: 'TL'": continent_name = 'AS' else: continent_name = 'N/A' return continent_name
内容的提问来源于stack exchange,提问作者Yuri Reis Valete
相关产品推荐
相关产品推荐

