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

Jupyter Notebook中try-except代码块异常执行问题求助

为什么try块部分代码和except块都会执行

你的代码执行逻辑很明确,原因如下:

  1. 代码先执行print('time :' , datetime.now()),输出时间信息,这部分正常运行。
  2. 进入try块后,先执行了第一个print("Command executed"),所以你会看到这行输出。
  3. 紧接着执行pd.read_sql('''select * from table ''')时触发了异常——大概率是因为pd.read_sql必须传入数据库连接对象con(你没指定要连接哪个数据库),也可能是表不存在、SQL语法错误或数据库未正常连接。
  4. Python遇到异常后,会立刻终止try块内剩余代码的执行(第二个print("Command executed")根本没运行),直接跳转到except块执行print("Command skipped")。

如果想排查具体异常原因,不要用空的except块,改成捕获异常并打印详情,代码可以调整为:

import datetime
import pandas as pd

print('time :' , datetime.now())
try:  
    print("Command executed")
    # 记得补充数据库连接对象con,比如你的数据库连接实例
    pd.read_sql('''select * from table  ''', con=your_db_connection)
    print("Command executed")
except Exception as e:
    print(f"Command skipped,异常详情:{e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:15:41