为何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
相关产品推荐
相关产品推荐

