Warmup

  1. Write a function called first_and_last that takes a string as input.

  2. The function should return a new string made up of:

    • the first character of the input string, and
    • the last character of the input string.

Examples:

first_and_last("Python")   # returns "Pn"
first_and_last("cat")      # returns "ct"
first_and_last("a")        # returns "aa"

Agenda

  • Monday: Unit 4 Review
  • Tuesday: Unit 4 Quiz (20 questions, Canvas)
  • Wednesday: Midterm Review
  • Friday: Python Midterm (40 questions, Canvas)

Lesson 4.6: Raising Exceptions

Review

  • Exceptions happen when something goes wrong in a program
  • try/except lets us handle those problems
  • Now: how do we make our own exceptions?

The raise Keyword

  • Use raise to trigger an exception on purpose
def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("You can’t divide by zero!")
    return a / b

print(divide(10, 2))
print(divide(10, 0))  # raises ZeroDivisionError

Why Raise Exceptions?

  • Stops bad data from breaking the program later
  • Makes code more predictable
  • Forces errors to be handled where appropriate

Raising Built-in Exceptions

  • Common ones to raise:
    • ValueError
    • TypeError
    • ZeroDivisionError
def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

Raising Custom Messages

  • Add helpful error messages for debugging
x = -5
if x < 0:
    raise ValueError("x must not be negative")

Raising in Functions

  • Functions can enforce rules
def square_root(n):
    if n < 0:
        raise ValueError("Cannot take square root of negative number")
    return n ** 0.5

Quick Check

  • What does raise do in Python?
  • Why would you raise an exception instead of just printing a message?
  • Which built-in exceptions might you raise for invalid input?

Practice Challenge

Write a function get_grade(score) that:

  • Raises a ValueError if the score is less than 0 or greater than 100
  • Otherwise returns the letter grade (A, B, C, D, F)