liveBook · Manning

Try-catch block

As explained in Software Engineering for Data Scientists

A try statement is Python syntax that encloses code whose exceptions may be handled by associated clauses.

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

How Software Engineering for Data Scientists covers it

How deep it goes
Explains try, except, Exception, finally, and error recording through a focused workflow, without covering broader exception design.
Examples
Uses yahoo_fin stock downloads, valid and invalid ticker symbols, failures lists, progress messages, and recorded exception types.
What it assumes
Assumes basic Python loops, dictionaries, lists, function calls, and indentation while teaching exception handling through zero-frills examples.
What you can do after
Apply try/except/finally to continue batch downloads, track failures, log progress, and inspect exception types.
How it connects
Connects exception handling with loops, web requests, logging, failure tracking, and finally clauses.

Also explained in

Compare how 12 books explain try-catch block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Engineering for Data Scientists. The section links point to the parts of the book it draws on.