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:
| Exception | Usual meaning | First place to look |
|---|---|---|
TypeError | value of the wrong type used in an operation | mixing str and int, or a variable that is None |
ValueError | right type, unacceptable content | parsing: int("12px") |
KeyError | dictionary key does not exist | typo in the key, or data missing a field |
IndexError | list index past the end | off-by-one, or an empty list |
AttributeError | object has no such attribute or method | typo, wrong type, or a method that returned None |
NameError | variable or function name not defined | typo, 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?