【问题标题】:Evaluating multiple conditions in try block in Python在 Python 的 try 块中评估多个条件
【发布时间】:2023-01-11 08:55:48
【问题描述】:
是否可以在 Python 的 try 块中评估多个条件。下面是案例。
我有以下2个条件。
- 连接到 sql server 以将数据读入两个数据帧。代码中存在超时,如果连接时间超过 15 秒,代码应引发异常并退出。
- 检查这两个dataframe是否有数据。如果其中一个dataframe为空,则退出代码,如果没有则继续else块中的代码。
我目前正在考虑这样做。有没有更优雅的方式。
try:
#Condition 1
except:
#Condition 1
try:
#Condition 2
except:
#Condition 2
else:
#Condition 3
【问题讨论】:
标签:
python
pandas
try-except
【解决方案1】:
r如果您只想捕获不同的错误情况,那么您可以包含连接到服务器的代码,然后在 try 语句中测试数据。然后在 except 语句中指定要捕获的错误:
def connect_to_server(db):
# Connection Code
if connection_timed_out:
raise my_timeout_exception #either a custom error you have created or propagate standard error from connection timeout
return connection
def read_database(conn):
#read db into dataframe code
if dataframe_isempty:
raise empty_df_exception #either a custom error you have created or propagate standard error from dataframe reading
return dataframe
try:
using_con = connect_to_server(db)
df = read_database(using_con)
except my_timeout_exception:
handle_error_1
break
except empty_df_exception:
handle_error_2
break
else:
continue_code
如果处理代码相同(例如,只是一个 break 语句),您实际上可以在一个 except 语句中包含两个异常。