AI summary by TwinMind

Lecture 13: Exceptions and Assertions

MIT OpenCourseWare

42m 55s

Introduction and Debugging Ducks

  • Professor distributing leftover debugging ducks from previous lecture
  • Encourages students to adopt them for debugging strategies
  • Mentions carrying debugging duck on phone for daily programming use

Exceptions Overview

  • Exceptions are "scary red errors" when programs crash
  • Previously encountered: IndexError, TypeError, SyntaxError, NameError
  • Up to now, exceptions caused immediate program crashes with no handling mechanism
  • Python allows writing code to handle exceptions instead of crashing

Try-Except Block Structure

  • try keyword starts code block with potentially problematic code
  • If code executes successfully without exceptions, except block ignored
  • If exception raised, execution stops in try block, jumps to except block
  • Analogy to if-else: if code works (pass), else handle the problem
  • Basic syntax: try → potentially problematic code, except → error handling code

Sum Digits Example - Without Exception Handling

  • Function sum_digits(s) takes non-empty string containing digits
  • Returns sum of all digit characters in string
  • Uses if char in '0123456789' to check if character is digit
  • Casts digits to integers and adds to running total
  • Example: "123" returns 6, "123abc" returns 6 (ignores non-digits)
  • Without if statement, casting 'a' to int throws ValueError

Sum Digits Example - With Exception Handling

  • Removes if statement, assumes all characters can be cast to integers
  • Wraps int(char) and total += int(char) in try block
  • Except block prints "can't convert" + character when ValueError occurs
  • Loop continues to next character after handling exception
  • Example: "123abc" outputs conversion errors for a, b, c but still calculates sum

User Input Exception Handling

  • User input highly unpredictable, good candidate for try-except
  • Example: getting two numbers, dividing first by second
  • Potential errors: ValueError (non-numeric input), ZeroDivisionError (divide by zero)
  • Generic except block prints "bug in user input" for any error

Specific Exception Handling

  • Can have multiple except blocks for different exception types
  • except ValueError: catches only ValueError exceptions
  • except ZeroDivisionError: catches only division by zero
  • Generic except: catches any other unspecified exceptions
  • Allows custom responses for different error types
  • Example: ValueError → "could not convert to number", ZeroDivisionError → "can't divide by zero, a/b is infinity"

Additional Try Block Components

  • else block: executes only if try block completes without exceptions
  • finally block: always executes regardless of exceptions
  • Finally useful for cleanup code (e.g., closing files)
  • Not commonly used in this class but good to know

Exception Handling Strategies

  • Fail silently: catch exception, do nothing (not recommended)
  • Silent substitution: replace bad values without notification (not recommended)
  • Flag errors: print error messages to user (minimum recommended)
  • Return error values: set flag variables, check later (complicates code)
  • Raise custom exceptions: crash on own terms with custom messages

Raising Custom Exceptions

  • raise keyword allows throwing own exceptions
  • raise ValueError("custom message") creates custom error with specific message
  • Example: sum_digits raises ValueError("string contained a character") instead of cryptic default message
  • Program still crashes but with clearer, more helpful error message

Pairwise Division Exercise

  • Function takes two non-empty lists of equal length
  • Returns new list with element-wise division: [4,5,6] / [1,2,3] = [4.0, 2.5, 2.0]
  • If denominator contains zeros, raise ValueError with nice message
  • Solution uses try-except around division operation
  • Alternative: check for zeros before processing with if 0 in l_denom:

Introduction to Assertions

  • Assertions are special type of exceptions for defensive programming
  • Used to enforce contracts between function writers and users
  • Help enforce docstring specifications programmatically
  • assert condition, "error message" syntax
  • If condition true, code continues; if false, raises AssertionError

Assert Statement Mechanics

  • Halts execution immediately when contract violated
  • Prevents bad values from propagating through program
  • Makes debugging easier by catching problems early
  • Better than letting bad values travel through multiple function calls

Sum Digits with Assertions

  • Add assert len(s) != 0, "s is empty" to enforce non-empty string requirement
  • If empty string passed, AssertionError raised immediately
  • Provides clear message about contract violation

Pairwise Division with Assertions

  • assert len(l_num) == len(l_denom), "list lengths different"
  • assert len(l_num) != 0, "empty list"
  • Enforces equal length and non-empty requirements
  • Multiple assertions can be used to check different conditions

Class Grades Example - Data Structure

  • Complex nested list structure: list of students
  • Each student: [name_list, grades_list]
  • name_list: [first_name, last_name]
  • grades_list: [grade1, grade2, ...]
  • Goal: add average grade as third element for each student

Class Grades - Average Function Variations

  • Basic version: sum(grades) / len(grades)
  • Problem: crashes with ZeroDivisionError if student has no grades
  • Try-except version: catches ZeroDivisionError, prints warning, returns None
  • Improved version: catches error, prints warning, returns 0 instead of None
  • Assert version: assert len(grades) != 0, "no grades data" - crashes if no grades

Summary Points

  • Exceptions not as scary as initially appear
  • Don't always have to terminate program
  • Can catch, handle appropriately (print messages, set defaults, custom termination)
  • Exception handling crucial for robust programs, especially with user input
  • Assertions are special exceptions for enforcing specifications
  • Assertions prevent bad values from propagating through code
  • Use assertions to catch problems early in development process

TwinMind

Get summaries like this for your own meetings

TwinMind takes notes in the background during meetings, lectures, and calls, then writes the summary for you.

Free plan to get started

No bot joins your calls

Phone, desktop & Chrome apps

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome