TracksGuided Small Projects With AI AssistanceProject One: CLI ScriptError Handling and Edge Cases(8 of 9)

Error Handling and Edge Cases

Real-world programs encounter problems. Networks fail, APIs return errors, users provide invalid input. Good error handling transforms cryptic crashes into helpful messages that guide users toward solutions.

Types of Errors to Handle

Your stock fetcher might encounter several error categories:

Network errors: No internet connection, DNS failures, timeouts. These happen outside your control.

API errors: Rate limiting (too many requests), authentication failures, server errors. The API is telling you something went wrong.

User input errors: Invalid stock symbols, empty input, malformed arguments. The user made a mistake.

Data errors: Unexpected API response format, missing fields. The data isn't what you expected.

Each type deserves a different message and potentially different handling.

Writing Helpful Error Messages

Compare these two error experiences:

# Bad: cryptic and unhelpful
KeyError: 'Global Quote'

# Good: explains what happened and what to do
Error: Could not find stock symbol 'XYZ123'.
Please check the symbol and try again.
Valid symbols look like: AAPL, GOOGL, MSFT

Good error messages answer three questions: What happened? Why? What should I do now?

Implementing Error Handling

Wrap risky operations in try/except blocks:

import requests

def get_stock_price(symbol):
    try:
        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
    except requests.exceptions.Timeout:
        raise StockFetchError(
            f"Request timed out. The API might be slow. "
            f"Try again in a moment."
        )
    except requests.exceptions.ConnectionError:
        raise StockFetchError(
            f"Could not connect to the API. "
            f"Check your internet connection."
        )
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 429:
            raise StockFetchError(
                f"Rate limit exceeded. "
                f"Wait a minute before trying again."
            )
        raise StockFetchError(f"API error: {e.response.status_code}")

Asking AI for Edge Cases

AI can help identify scenarios you might miss:

What edge cases should I handle in a stock price fetcher?
Consider network issues, API limitations, and user input problems.

AI might suggest handling empty responses, partial data, API maintenance windows, or symbols with special characters.

Graceful Degradation

Sometimes you can partially succeed. If a user requests five symbols and one fails, show results for the four that worked plus an error for the one that didn't:

AAPL: $178.50
GOOGL: $141.80
INVALID: Error - Symbol not found
MSFT: $378.90

This is more useful than failing entirely because one symbol was wrong.

See More

Last updated December 13, 2025

You need to be signed in to leave a comment and join the discussion