You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Python的except语句未捕获SSL相关链式错误?如何精准处理?

问题解析与解决方案

为什么你的except语句未能捕获错误?

核心原因是你捕获的异常类和实际抛出的异常类来自不同模块,导致类型不匹配:

  • 代码中写的SSLError如果是从ssl模块导入,但实际抛出的是requests.exceptions.SSLError
  • MaxRetryError属于urllib3.exceptions.MaxRetryError,若未正确导入该模块的类,捕获会失效
  • SSLCertVerificationError是ssl.SSLCertVerificationError,但它被上层requests.SSLError包装,不会直接被外层except捕获

精准捕获这些异常的正确方式

步骤1:导入对应模块的异常类

import ssl
from urllib3.exceptions import MaxRetryError
from requests.exceptions import SSLError as RequestsSSLError

步骤2:修改try-except块

按从具体到通用的顺序捕获异常:

try:
    allocation['Price_Data_Cut'], allocation['Price_Current'], allocation['Ticker_CHK'] = zip(*allocation['ETF'].\
        apply(ticker_info, 1, args=(data_cut_datetime,)))
except RequestsSSLError as e:
    # 捕获requests包装的SSL错误,覆盖底层证书验证、重试耗尽等场景
    display('SSL Related Error, prices not fetched')
    pass
except MaxRetryError as e:
    # 捕获可能直接抛出的重试耗尽错误
    display('Max retries exceeded, prices not fetched')
    pass
except ssl.SSLCertVerificationError as e:
    # 捕获最底层的证书验证失败错误
    display('Certificate verification failed, prices not fetched')
    pass

补充说明

requests.SSLError是上层包装类,会包裹urllib3.MaxRetryError和ssl.SSLCertVerificationError,因此捕获RequestsSSLError就能覆盖绝大多数场景。若需区分具体错误类型,可通过e.__cause__访问底层异常做精细化处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 02:02:01