Back to website
Mayank Aggarwal Learning Center

Phase 02 · Python FoundationsLesson 7 of 8

Error & Exception Handling

Write programs that fail gracefully instead of crashing.

  • 2:11:53 video
  • 2 min read
  • Intermediate
  • Deep dive
01

The problem

Things go wrong in every real program: a file is missing, a user types letters instead of a number, an API times out. Without error handling, any of these crashes your whole program. With it, your code can recover gracefully, retry, or at least fail with a clear message.

02

The concept

Deep dive: 2h 12m video. You don’t need it all in one sitting. Watch the first 20 minutes for the core idea, read the write-up below, and come back for the rest when you need it.

Errors vs exceptions#

  • Syntax errors mean the code itself is invalid (a missing colon or bracket). Python won't run it at all.
  • Exceptions happen while the program runs: ZeroDivisionError, ValueError, FileNotFoundError, KeyError and so on. These are the ones you can catch.

try and except#

Put the risky code in try, and handle the failure in except:

Python
try:
    age = int(input("Your age: "))
except ValueError:
    print("Please enter a whole number.")

If the conversion fails, Python jumps straight to the matching except block instead of crashing.

The full shape: else and finally#

Python
try:
    f = open("data.csv")
    rows = f.readlines()
except FileNotFoundError:
    print("data.csv is missing")
else:
    print(f"Loaded {len(rows)} rows")   # runs only if no exception
finally:
    print("Done.")                     # always runs
BlockRuns when
tryAlways, first
exceptOnly if a matching exception occurs
elseOnly if no exception occurred
finallyAlways, even after errors or return. Ideal for cleanup

The path through try, except, else and finally

  1. tryalways runs first
  • matching exception
    1. excepte.g. "data.csv is missing"
    2. finallyalways runs
  • no exception
    1. elsee.g. "Loaded N rows"
    2. finallyalways runs

Catch specific exceptions#

Python
# Bad: hides every possible bug
try:
    process(order)
except:
    pass

# Good: handle only what you expect
try:
    process(order)
except KeyError as e:
    print(f"Order is missing field: {e}")

Raising your own exceptions#

Use raise when your code detects a problem it can't handle:

Python
def set_temperature(t):
    if not 0 <= t <= 2:
        raise ValueError("temperature must be between 0 and 2")

For larger projects, define custom exceptions so callers can handle them precisely:

Python
class RateLimitError(Exception):
    pass

Why this matters for AI work#

LLM and API calls fail regularly: rate limits, timeouts, malformed JSON in a model's reply. Production AI code wraps these calls in try/except, retries with a delay, and logs what went wrong. The patterns in this lesson are exactly what keeps an agent running when one step fails.

03

Try it

Your task · about 10 minutes

Ask the user for a number and keep asking until they type a valid integer, using try/except ValueError.

04

Recap & next

Key takeaways

  1. Wrap risky code in try, and handle failures in except.
  2. Catch specific exceptions (except ValueError:) rather than a bare except:.
  3. else runs only when no exception occurred; finally always runs, which makes it ideal for cleanup.
  4. Use raise to signal errors yourself, and subclass Exception for custom error types.

Quick check

2 questions · instant feedback

1When does a finally block run?
2Why catch specific exceptions instead of a bare except:?

Finished this lesson?

Mark it complete to track your progress and keep your streak going.

Next