RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Fredoline Eruo
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Python for AI — Zero to Useful
  6. /Ch. 9
Python for AI — Zero to Useful

09. Error Handling

Chapter 9 of 36 · 20 min
KEY INSIGHT

Catch specific exceptions, not bare `except Exception`. This prevents masking bugs. Use `raise` to fail fast when inputs are invalid—silent failures cause worse bugs than loud ones.

Try/Except

def divide(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        return 0
    except TypeError:
        return None

Catching Multiple Exceptions

try:
    result = int(user_input) / divisor
except (ValueError, ZeroDivisionError) as e:
    print(f"Error: {e}")
    result = None

The Exception Object

try:
    data = json.loads(invalid_json)
except json.JSONDecodeError as e:
    print(f"Failed to parse JSON at position {e.pos}")
    print(f"Error: {e.msg}")

Finally

try:
    file = open("data.json")
    data = json.load(file)
finally:
    file.close()  # Always runs

Or use with to avoid explicit close:

try:
    with open("data.json") as f:
        data = json.load(f)
except FileNotFoundError:
    data = {}

Raising Errors

def call_api(model_name):
    valid_models = ["gpt-4", "gpt-3.5-turbo", "claude-3"]
    if model_name not in valid_models:
        raise ValueError(f"Unknown model: {model_name}. Valid: {valid_models}")
    # ... proceed with API call

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Write a function parse_temperature that accepts a string input, converts it to float, and raises a ValueError if the value is outside 0.0 to 2.0. Handle the ValueError when calling the function with invalid input.

← Chapter 8
File I/O
Chapter 10 →
NumPy Arrays for ML