Lesson 35/48 ยท ๐ŸŒ Real World Python
๐ŸŒ Real World PythonLesson 35/48
Phase 7 ยท Real World Python22 min

Error Handling, try / except

Write programs that survive mistakes instead of crashing

Every real program will encounter errors, a file that doesn't exist, invalid user input, a network timeout. Exception handling lets your program deal with these situations gracefully instead of crashing.

How would you approach this? Think first, then expand.

Basic try/exceptpython
# Without error handling, crashes on bad input
number = int("abc")   # ValueError: invalid literal for int()

# With error handling
try:
    number = int("abc")
    print(f"Got: {number}")
except ValueError:
    print("That wasn't a valid number!")
# Output: That wasn't a valid number!
๐Ÿ”Code TracerStep 1 / 4
trace.py
1try:โ†
2 x = int("hello")
3 print("no error")
4except ValueError as e:
5 print(f"Caught: {e}")
Variables
No variables yet
Step 1 / 4
How it works:
  • Python tries to run the try block
  • If an exception occurs, it jumps to the matching except block
  • If no exception occurs, the except block is skipped
  • Catching specific exception types
    Always catch the most specific exception you can, it makes bugs easier to diagnose:
    Multiple except clausespython
    def safe_divide(a, b):
        try:
            result = a / b
            return result
        except ZeroDivisionError:
            print("Error: cannot divide by zero")
            return None
        except TypeError:
            print("Error: both arguments must be numbers")
            return None
    
    print(safe_divide(10, 2))   # 5.0
    print(safe_divide(10, 0))   # Error: cannot divide by zero
    print(safe_divide(10, "x")) # Error: both arguments must be numbers
    ๐Ÿค”Quick Check

    What is the correct order for except clauses when catching both ValueError and Exception?

    else and finally
  • else: runs only if NO exception occurred
  • finally: ALWAYS runs, regardless of whether an exception occurred (used for cleanup)
  • else and finallypython
    def read_number():
        try:
            n = int(input("Enter a number: "))
        except ValueError:
            print("Not a valid number")
        else:
            print(f"You entered: {n}")   # only if no exception
        finally:
            print("Done.")               # always runs
    
    # Simulating with a fixed value:
    try:
        n = int("42")
    except ValueError:
        print("Not a valid number")
    else:
        print(f"You entered: {n}")
    finally:
        print("Done.")
    # You entered: 42
    # Done.
    raise, trigger an exception yourself
    Use raise to signal that something is wrong in your own code:
    Raising exceptionspython
    def set_age(age):
        if age < 0 or age > 150:
            raise ValueError(f"Age {age} is not realistic")
        return age
    
    try:
        set_age(-5)
    except ValueError as e:
        print(f"Error: {e}")   # Error: Age -5 is not realistic
    ๐Ÿค”Quick Check

    When does the finally block execute?

    ๐ŸŒIn the Real World...

    Your pipeline script must handle: API timeouts, missing config files, invalid YAML, permission denied errors, network failures. try/except is the difference between a script that crashes and one that recovers.

    Practice Exercises

    0/3 solved
    Exercise 1 of 3easyGuided
    โฑ 00:00

    Safe Integer Input

    Wrap the int() conversion in a try/except so that invalid input prints an error message instead of crashing.
    Given: user_input = "hello"Expected output: Error: "hello" is not a valid integer
    solution.py
    1 / 3
    Exercise 2 of 3easy
    โฑ 00:00

    Safe Division

    Write a function divide(a, b) that returns a / b but prints "Cannot divide by zero" and returns None if b is 0.
    - print(divide(10, 2)) โ†’ 5.0- divide(10, 0) โ†’ prints Cannot divide by zero, returns None
    solution.py
    2 / 3
    Exercise 3 of 3medium
    โฑ 00:00

    Validate Age

    Write a function validate_age(age) that:- Raises ValueError if age is not an integer- Raises ValueError if age < 0 or > 120- Returns age if valid
    Call it with age = -5 and catch the error:Expected output: Invalid age: -5 is out of range
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion