Jupyter Notebook中try-except代码块异常执行问题求助
为什么try块部分代码和except块都会执行
你的代码执行逻辑很明确,原因如下:
- 代码先执行
print('time :' , datetime.now()),输出时间信息,这部分正常运行。 - 进入
try块后,先执行了第一个print("Command executed"),所以你会看到这行输出。 - 紧接着执行
pd.read_sql('''select * from table ''')时触发了异常——大概率是因为pd.read_sql必须传入数据库连接对象con(你没指定要连接哪个数据库),也可能是表不存在、SQL语法错误或数据库未正常连接。 - 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
相关产品推荐
相关产品推荐

