A raise statement explicitly signals an exception and can stop the current execution path. In a data workflow, use it when a required database query returns no records, preventing later processing from consuming time and compute on missing data. section 3.6.4
Stop processing when a query returns no rows
After reading customer features with pandas.read_sql, check the number of returned rows and raise an exception when it is zero: if customer_key_features.shape[0] == 0: raise Exception("Empty data returned"). This stops subsequent processing and reports why the workflow cannot continue. section 3.6.4
Use the raise statement to:
- Alert users that a required condition has failed. section 3.9
- Stop a sequence of dependent files or processing steps when data extraction returns zero records. section 3.6.4
- Prefer raise for explicit error signaling, while assert checks a condition and raises an AssertionError when false. section 3.9
Listing 3.48 Modify process_data function to raise an Exception error if no rows are returned. This updated script is named read_from_customer_database_using_error_handling.py in the ch3 directory.
import pandas as pd #1
import pyodbc #1
conn = pyodbc.connect("DRIVER={SQLite3 ODBC Driver}; #2
SERVER=remotehost123; #2
DATABASE=customers.db;Trusted_connection=yes") #2
def process_data(conn = conn):
customer_key_features = pd.read_sql(conn, #3
"""SELECT churn, #3
total_day_charge, #3
total_intl_minutes, #3
number_customer_service_calls #3
FROM customer_data""") #3
# if zero rows are returned,
# raise an Exception #4
if customer_key_features.shape[0] == 0: #4
raise Exception("Empty data returned") #4
[...additional code] #5
Inspect the complete database-processing example that adds a row-count check and raises an exception for empty query results. section 3.6.4


