You need to enable JavaScript to run this app. 如何将父函数的try/except错误校验逻辑应用到其调用的子函数上?
优惠活动
大模型
产品
解决方案
定价
更多

如何将父函数的try/except错误校验逻辑应用到其调用的子函数上?

异常未捕获原因及解决方案

核心原因

你遇到的问题90%以上是异常类匹配错误导致的:

  • Python内置了ConnectionError异常类,但requests库发起请求时抛出的连接异常是独立定义的requests.exceptions.ConnectionError,二者不属于同一继承链,你当前代码只捕获了内置ConnectionError,自然抓不到requests抛出的连接异常。
  • 小概率原因是download_file函数内部写了独立的try/except逻辑,没有把捕获到的异常重新抛出,导致外层无法感知。

解决方法

方案1:修正异常捕获规则(最简洁)

直接扩大异常捕获范围,覆盖requests相关的所有请求异常即可,修改你代码中的except分支:

import requests
# 其余原有导入不变

for file_name, remote_path in file_paths.items():
    while True:
        try:
            # 原有逻辑不变
            local_file_date = datetime.fromtimestamp(os.path.getmtime(file_name))
            api_url = f"https://api.github.com/repos/owid/covid-19-data/commits?path={remote_path}&per_page=1"
            last_updated = requests.get(api_url).json()[0]['commit']['committer']['date']
            remote_file_date = datetime.strptime(last_updated, "%Y-%m-%dT%H:%M:%SZ")
            delta = (remote_file_date - local_file_date).days
            if delta >= 0:
                choice = input(f"{file_name} is OUTDATED. It's roughly {str(delta + 1)} days old. "
                               "Would you like to update it? (Y/N): ")
                if "y" in choice.lower():
                    download_file(file_name, remote_path)
            break
        # 同时捕获内置连接异常和requests所有请求异常,覆盖所有网络相关报错
        except (ConnectionError, requests.exceptions.RequestException):
            print("CAN'T CONNECT TO THE INTERNET! Your files might be out of date."
                  "Try checking your internet connection or Github's status.")
            return

requests.exceptions.RequestException是requests所有请求异常的基类,能覆盖连接错误、超时、响应解析错误等所有请求相关的异常,避免漏捕。

方案2:排查download_file逻辑

如果修改捕获规则后依然无法捕获异常,检查download_file内部是否有独立的try/except逻辑,如果有,要么去掉不必要的异常捕获让异常向上抛出,要么捕获后执行完内部逻辑后用raise关键字重新抛出异常:

def download_file(file_name, remote_path):
    try:
        # 原有下载逻辑
        resp = requests.get(xxxx)
        # 写文件逻辑
    except SomeError as e:
        # 你需要先执行的内部逻辑,比如删除不完整的本地文件
        if os.path.exists(file_name):
            os.remove(file_name)
        # 重新抛出异常,让外层update_data的异常捕获逻辑处理
        raise

额外优化建议

你当前的代码只要遇到一次网络错误就直接终止所有文件的更新检查,如果你需要批量更新多个文件,可以把return改为break或者continue,根据你的需求调整异常后的处理逻辑即可。

内容的提问来源于stack exchange,提问作者Konrad Gr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 08:54:03