未找到值时生成器表达式触发StopIteration,try-except处理是否正确?
问题解答
你的try-except处理方式是可行的,但有两个可以优化的点,让代码更健壮、逻辑更清晰:
1. 避免捕获所有异常
你当前的except:会捕获所有类型的异常(比如KeyError——如果某个Profile字典缺少Name/ID键、文件读取异常等),这会掩盖其他潜在问题。应该明确只捕获StopIteration:
Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []} name = "asdadsefttytryrty" try: get = next(get for get in Data["Profiles"] if get["Name"] == name or get["ID"] == name) print("exist") except StopIteration: print("Doesn't exist")
2. 用next()的默认参数简化逻辑
next()函数支持传入第二个参数作为迭代耗尽时的默认值,这样可以不用异常处理,直接通过if-else判断结果,代码更直观:
Data = json.load(open(file)) if isfile("data.json") else {"News": {},"Records": {},"Profiles": []} name = "asdadsefttytryrty" # 用括号包裹生成器表达式避免语法歧义 get = next((item for item in Data["Profiles"] if item["Name"] == name or item["ID"] == name), None) if get is not None: print("exist") else: print("Doesn't exist")
额外优化建议:文件加载部分用with语句自动关闭文件,避免资源泄漏:
from os.path import isfile import json file_path = "data.json" if isfile(file_path): with open(file_path, 'r') as f: Data = json.load(f) else: Data = {"News": {},"Records": {},"Profiles": []}
内容的提问来源于stack exchange,提问作者DG Nutria
相关产品推荐
相关产品推荐

