Exceptions and Assertions
MIT 6.100L Intro to CS and Programming using Python, lecture 13, explained in plain English
Want this lecture to stick? In LessonBound you get checked practice questions for every part, can ask about anything you don't get, and can listen with your screen off. Free, no ads.
Learn this lecture freeWatch or read the original lecture: MIT OpenCourseWare.
Part 1 · 0:00–10:00
This part explains what exceptions are and how try and except blocks let Python handle an error instead of crashing.
Key ideas
- An exception is what happens when your code hits an unexpected condition. Index errors, type errors, and name errors are all examples. 1:15
- Until now, when an exception happened, the program crashed right away and you had no way to handle it. Python lets you write code that deals with the problem instead. 2:16
- You put the risky code inside a try block. If that code runs without an error, the except block is skipped. If an error happens, Python stops the rest of the try block and jumps to the except block. 3:42
- In the some digits example, an if check stops letters from being turned into numbers. Without that check, casting the letter 'a' to an integer causes a ValueError. 7:40
- With a try and except, the bad character causes a message to print, and the loop moves on to the next character instead of crashing. 9:05
Words to know
- exception
- An error that happens while the program runs, which would normally make it stop.
- try
- A keyword that starts a block of code Python should attempt. If something goes wrong in it, Python can catch the problem.
- except
- A keyword for the block of code that runs only when an error happens inside the matching try block.
- ValueError
- A type of error Python raises when a value is the wrong kind for the job, such as trying to turn the letter 'a' into a number.
Example
Think of a try block like a careful step on a bridge with a safety net. If the step holds, you keep walking and the net is never used. If you slip, the net catches you and you can decide what to do next, instead of falling all the way down.
3 checked practice questions for this part are in the app.
Part 2 · 10:00–20:00
This part shows how to use try and except blocks to catch errors, especially from user input, and how to handle those errors in a friendlier way.
Key ideas
- An exception is an error that stops a program while it runs. A try block holds the code that might cause one, and an except block holds the code that runs if it happens. 10:17
- User input is unpredictable, so it is a common place to use try and except. Users may type letters when you asked for numbers, or they may enter zero as a divisor. 10:38
- You can write a different except block for each kind of error, so each error can get its own specific message. An except block runs only when its named error happens. 13:09
- Do not hide errors by failing silently, and do not let bad values pass through without a warning. At the least, print a message so people know something went wrong. You can also stop the program on purpose, in a controlled way. 18:17
Words to know
- exception
- An error that happens while a program runs and that the program does not know how to handle on its own.
- ValueError
- The name of the error Python raises when a value cannot be converted to the right type, such as turning the letter a into a number.
- ZeroDivisionError
- The name of the error Python raises when a program tries to divide a number by zero.
- finally block
- A block of code that runs every time, whether or not an error happened. It is often used for clean-up, such as closing files.
Example
Think of a shop cashier who gets a bad card from a customer. A good cashier does not ignore the problem or close the till with no explanation. They say what went wrong, like card not accepted, and they handle that exact problem in a calm, clear way. The try and except blocks in code work the same way.
3 checked practice questions for this part are in the app.
Part 3 · 20:00–30:00
This part shows how to stop a program on purpose with your own error message, and how assertions help you catch bad inputs early.
Key ideas
- You can raise your own error with your own message. The code still stops, but you control what the error says. 20:00
- Put the risky code in a try block and catch the error with an except block. Then raise a ValueError with a clearer message, instead of printing something and letting the code keep going. 21:01
- In the pairwise division exercise, if the denominator list contains a 0, raise a ValueError with a clear message. You can also raise it inside an if statement, not only inside an except block. 22:54
- An assertion is a special kind of error that checks a rule. It helps enforce the rules written in a function's docstring, which are the promises between the person who writes a function and the person who uses it. 28:02
- If an assertion is true, the code keeps running. If it is false, Python stops right away with an AssertionError, so bad values do not get passed along. 29:07
Words to know
- ValueError
- A type of error that Python raises when a function gets a value it cannot work with. You can raise one yourself and add your own message.
- assertion
- A check that says a condition must be true. If it is false, Python stops the program with an error.
- docstring
- The text written at the top of a function that explains what the function expects and what it returns.
- contract
- The agreement between the person who writes a function and the person who uses it, such as what inputs are allowed.
Example
The lesson's pairwise division function divides each number in one list by the matching number in another list. If a number in the second list is 0, the function should raise a ValueError with a message like 'denominator contains a zero'. That stops the function early with a message you chose, instead of a confusing crash.
3 checked practice questions for this part are in the app.
Part 4 · 30:00–42:49
This part shows how to use assert statements to stop a program right away when a rule is broken, and how to catch errors so the program can recover.
Key ideas
- If something is strange or an assumption is not met, stop the program right away. Otherwise a bad value can be passed along to other functions and cause confusing bugs later. 30:00
- An assert statement checks that a condition is true. If the condition is false, Python raises an AssertionError with your message and the program stops. If the condition is true, the code carries on as normal. 30:36
- A contract is a rule a function expects its inputs to follow. For example, the input lists must be non-empty and the same length. You can use assert statements to enforce these rules. 31:26
- You can catch an exception with a try and except block, so the program can print a friendly message or return a default value instead of crashing. For example, a ZeroDivisionError can be caught when a student has no grades. 38:06
- Assertions are a kind of exception. Use them to enforce contracts, and use exception handling when you expect weird things to happen and want the program to deal with them. 41:23
Words to know
- assert
- A check you write in code that says a condition must be true. If it is false, the program stops with an error.
- exception
- An error that happens while a program runs. It can stop the program, or you can catch it and deal with it in your own way.
- contract
- A rule about what a function expects its inputs to look like, such as a string that is not empty.
- propagate
- To pass along or spread. A bad value that is propagated keeps moving through the program and causes problems further on.
Example
Think of a bank teller who checks that a form has a signature before accepting it. If the signature is missing, the teller stops right away and sends the form back, instead of letting the incomplete form move through the whole bank. An assert works the same way: it stops the program at the first broken rule so the problem is easy to find.
3 checked practice questions for this part are in the app.
← Lecture 12: List Comprehension, Functions as Objects, Testing, and Debugging · Lecture 14: Dictionaries →
Notes written by AI (Claude) from the lecture's official transcript, so check anything important against the lecture. MIT OpenCourseWare · CC BY-NC-SA 4.0 · not affiliated with or endorsed by MIT. These notes are shared under the same license.
LessonBound · Free lecture notes · Privacy · Terms · New York