Course outline · 0% complete

0/29 lessons0%

Course overview →

The Exception Bestiary

lesson 8-2 · ~10 min · 24/29

Each exception type is a hint

The exception type on that last line narrows the hypothesis before you read any code. The six you will meet daily:

ExceptionUsual meaningFirst place to look
TypeErrorvalue of the wrong type used in an operationmixing str and int, or a variable that is None
ValueErrorright type, unacceptable contentparsing: int("12px")
KeyErrordictionary key does not existtypo in the key, or data missing a field
IndexErrorlist index past the endoff-by-one, or an empty list
AttributeErrorobject has no such attribute or methodtypo, wrong type, or a method that returned None
NameErrorvariable or function name not definedtypo, or using a name before defining it

One trap earns a special note: sort(), append(), and friends modify the list and return None. Save their return value and the next line blows up with a confusing NoneType message.

Code exercise · python

Run the bestiary in captivity: five classic mistakes, each caught, printing its exception type and message. Match each line against the table above.

Problem

A colleague writes nums = nums.sort() and on the next line nums[0] crashes with "'NoneType' object is not subscriptable". What is the exception TYPE of that crash?

Code exercise · python

Your turn: that exact trap, live. top_three crashes with TypeError: 'NoneType' object is not subscriptable. Fix it with sorted() so it prints: [95, 91, 88]

Quiz

A trace ends with: AttributeError: 'NoneType' object has no attribute 'strip'. What is the strongest hypothesis?

Quiz

A trace ends with: ValueError: invalid literal for int() with base 10: ' 42px'. Which hypothesis does that one line hand you directly?