A try statement encloses code that might raise an exception. An associated except clause handles a selected error so execution can continue instead of stopping. section 3.6.3
Continue downloading valid tickers
When downloading stock data, place the request inside try and record invalid symbols in except: try: all_data[ticker] = si.get_data(ticker); except AssertionError: failures.append(ticker). The loop can then process later tickers. Use except Exception to catch any error, though the focused AssertionError handler identifies the expected failure. section 3.6.3
Related clauses extend the basic statement:
- finally runs whether the try code succeeds or an exception is handled. section 3.6.3
- except Exception as error allows the failure type to be stored for investigation. section 3.6.3
Listing 3.43 This time we use a try/except block to handle the AssertionError that arises when an invalid stock ticker is passed to the web request. The exception block here will bypass the error, tracking the stock ticker in a failures list, and the code execution will proceed to the next ticker in the list (rather than exiting the loop with an error). You can run this code yourself using ch3’s download_tech_stock_prices_including_error_handling.py file.
all_data = {} #1
failures = [] #2
for ticker in tickers: #3
try: #4
all_data[ticker] = si.get_data(ticker) #4
print(ticker + " downloaded SUCESSFULLY") #4
except AssertionError: #5
failures.append(ticker) #5
print(ticker + " download FAILED") #5
Inspect the focused stock-download example with try/except, failure tracking, and progress messages. section 3.6.3











