Warmup

  1. Write a function called double_or_nothing that takes one number as input.
  2. If the number is positive, return double the number.
  3. If the number is zero or negative, return 0.

Write your function and test it.

Examples:

double_or_nothing(5)   # returns 10
double_or_nothing(-3)  # returns 0
double_or_nothing(0)   # returns 0

Agenda

Looking ahead

  • PE 1 Module 4
  • Makeups / Retests
  • Canvas Quiz Tuesday
  • Midterm Friday

Lesson 4.5: Handling Exceptions

Review

  • Errors (exceptions) stop programs if not handled
  • Common ones: ZeroDivisionError, ValueError, IndexError
  • We need a way to keep programs running

The try/except Block

  • Catches errors so the program doesn’t crash
try:
    num = int(input("Enter a number: "))
    print(10 / num)
except:
    print("Something went wrong!")

Catching Specific Exceptions

  • Better to catch specific exceptions than all at once
try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ValueError:
    print("That wasn’t a number!")
except ZeroDivisionError:
    print("You can’t divide by zero!")

Multiple Except Blocks

  • Can handle different errors in different ways
  • Order matters: Python checks top to bottom

A Safe Program

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Error: Division by zero"

print(safe_divide(10, 2))   # 5.0
print(safe_divide(10, 0))   # Error: Division by zero

Why Use Exception Handling?

  • Prevents program crashes
  • Provides helpful messages to users
  • Makes code more robust

Quick Check

  • What is the purpose of try/except?
  • Why should we avoid using a “bare” except:?
  • What’s the difference between catching specific vs. general exceptions?

Practice Challenge

Write a function to_int(s) that:

  • Tries to convert a string to an integer
  • Returns the integer if successful
  • Returns "Error: not a number" if it fails