Lesson · Exceptions & Defensive Programming
Built-in Exception Types
55 min readBuilt-in Exception Types
Built-in exception classes communicate common categories of failure. Choosing the most specific appropriate type makes APIs easier to debug and callers easier to write.
Learning goals
- Match a failure mechanism to its built-in exception type: bad value, wrong type, missing key, out-of-range index, missing attribute, operating system failure.
- Use an
isinstanceguard andraise TypeErrorthe wayget_itemdoes to reject an argument before touching the data. - Choose between catching a specific subclass such as
FileNotFoundErrorand its parentOSErrorbased on which failures a caller can actually handle. - Predict which exception
items[index]andmapping[key]raise when the index or key is not present.
Mental model
The type is a promise about the mechanism, not about the message: catching FileNotFoundError works without reading any text, because the class itself states which condition occurred. Python selects the type from the mechanism of the failure, so knowing the mechanism lets you predict which type will arrive. When you raise, pick the type that names the mechanism; when you catch, catch the narrowest type that covers the failures you can handle.
Mental model
read it top to bottom
value has the right type but is unacceptable → ValueError operation applied to an object of wrong type → TypeError mapping lookup with a missing key → KeyError sequence index outside the bounds → IndexError missing attribute on an object → AttributeError operating system or I/O failure → OSError library-defined failure with no specific type → RuntimeError
Core idea
Built-in exception types exist so failures can be classified by mechanism instead of by message. A ValueError says the value was wrong and a TypeError says the type was wrong, which lets callers select with except exactly the failures they can act on. The discipline is to raise the most specific type that is true of the situation and to let anything else keep its original type.
ValueError
ValueError signals that an operation received a value it cannot accept even though the type is acceptable, as in int("abc") or a negative number where only non-negative input is valid. Callers catch it when input can be well-typed yet still invalid. Raise it when a value fails a precondition that no more specific type describes.
TypeError
TypeError signals that an operation was applied to an object of an inappropriate type, as in len(5) or "a" + 1. It usually marks a programming error rather than bad external data, so it is rarely worth catching. Raise it when a function receives an argument whose type it cannot support.
KeyError
KeyError is raised when a mapping lookup names a key that does not exist, as in {"a": 1}["b"], and its message is the repr of the missing key. Prefer dict.get or an in check when a missing key is an expected outcome rather than an error. Catch it when the key comes from external input and the program can supply a fallback.
IndexError
IndexError is raised when an index into a sequence falls outside its bounds, as in [1, 2][5]. Negative indexes are valid down to -len(seq), so [1, 2][-3] raises as well. Catch it when the position comes from external input; when the position comes from your own loop bounds, the bug to fix is the bound arithmetic.
AttributeError
AttributeError is raised when attribute lookup fails because the object does not have the requested attribute, as in "text".push() or 42.missing. It often means the name was misspelled or the object is not the type you assumed. getattr(obj, name, default) treats a missing attribute as data instead of an error when that fits the design.
RuntimeError
RuntimeError is the general-purpose exception for failures that no more specific built-in type describes, such as a dictionary changing size during iteration. Libraries use it, or a subclass of it, when they need to signal an error of their own. When a more specific type fits, for example ValueError for a bad value, prefer that type.
OSError
OSError reports failures from the operating system: missing files, permission problems, full disks, and similar conditions. It carries an errno attribute with the numeric error code, and specific subclasses such as FileNotFoundError and PermissionError cover the common cases. Catch the specific subclass when you can, and the OSError parent only when you intend to handle the whole family.
Walkthrough
isinstance(index, int)guards the function's contract: anything else raisesTypeError("index must be int")before the lookup runs, soget_itemnever has to guess what a non-integer index meant.items[index]is the risky operation, and the surroundingexcept IndexErrorreplaces the interpreter's message withno item at index {index}, which names the offending position instead of only the sequence type.- The
raise IndexError(...)inside the handler runs after the original lookup failed and then travels to the caller. The success path isprint(get_item(["a", "b"], 1)), whereindex=1returns"b"without any exception. - Predict before running: which lines run for
get_item(["a", "b"], 5), and whatget_item(["a", "b"], "1")raises before any indexing happens.
Experiments to try
- Call
get_item(["a", "b"], 5)and compare its message with the interpreter's own["a", "b"][5]. Note what the custom message adds. - Call
get_item({"a": 1}, 0). Theisinstanceguard passes because0is anint, the dict lookup raisesKeyError, andexcept IndexErrordoes not match. Explain what now happens to the caller. - Remove the
isinstanceguard and callget_item(["a", "b"], "1"); read theTypeErrorthat the list raises and compare it with the guard's message. - Extend the function with an
except KeyErrorbranch that reports the missing key, then re-run the dict case from the second experiment and confirm which handler runs.
Common mistakes
- Raising
ExceptionorRuntimeErrorwhere a specific built-in fits: the message may read well, but callers can no longer catch the failure they can handle by type, so every handler degrades to matching strings. - Catching a broad parent such as
OSErrororExceptionaround more code than the operation that fails: unrelatedTypeErrororKeyErrorfrom other lines is silently absorbed too, and the real cause disappears from the traceback. - Assuming the sample data's size and shape hold for real input:
items[index]raisesIndexErrorandmapping[key]raisesKeyErroras soon as the data is shorter or sparser than the example. - Treating
OSErroras "file not found": the same base type also covers permission and disk failures, so a handler written for a missing file misreports a permission problem. CatchFileNotFoundErrorfor the case you can actually handle.
Practice: Easy
- For each of
int("abc"),len(5),{}["missing"],[1, 2][9], and"x".push(), predict the exception type first, then run it and record the real class and message. - Run the worked example's success case and then
get_item(["a", "b"], 5). Note what changes between the interpreter's nativeIndexErrorand the function's rerouted message. - Pick three of the seven types in this lesson and write one expression that raises each, using only literals and built-in operations.
Practice: Medium
- Extend
get_itemto accept mappings as well as sequences: add aKeyErrorhandler with its own message and keep theTypeErrorguard exact. Test it against a list, a dict, and a string index. - Write a
read_config(path)function that opens and returns the text of a file, and list theOSErrorsubclasses it can surface. Call it with a real file, a missing path, and a directory path, recording the class anderrnoin each case. - Find a
try/exceptin your own code that catches a broad type and narrow it to the specific types the protected operation can raise. List the exceptions you removed and what each could have hidden.
Practice: Hard
- Design a small
convertmodule whose functions turn raw text intoint,float, andbool. Document, for each function, the exact type it raises for a wrong argument type, an unparsable value, and an out-of-range value, then implement one function to that contract. - Build a failure lab with five prebuilt operations that raise
ValueError,TypeError,KeyError,IndexError, andOSError. First call them inside onetrywith a single handler, then split them so each failure reaches the handler that can respond. Compare what each layout reveals in the traceback. - Connect this lesson to custom exceptions (lesson 72): pick one failure in your own code, decide whether a built-in type or a subclass is the honest choice, and write the class or the
raiseline you would add.
Lesson checklist
- I can name the exception type for a bad value, a wrong type, a missing key, an out-of-range index, a missing attribute, and an OS failure.
- I can read
get_itemand point to the line that raisesTypeErrorand the line that raisesIndexError. - I can choose between catching
FileNotFoundErrorandOSErrorbased on which failures I can actually handle. - I can explain why raising a generic
Exceptioncosts callers the ability to catch the specific failure.
Remember
Built-in exception classes classify failures by mechanism: bad value, wrong type, missing key, out-of-range index, missing attribute, operating system error. Choosing the most specific type preserves that information at the boundary, because callers select with `except` by class, not by reading messages. Raise the type that names the mechanism, and catch the narrowest type you can handle.
Interview angles
What is the main purpose of **ValueError**?+
ValueError signals that an operation received a value it cannot accept even though the type is acceptable, as in int("abc"). Callers catch it when input can be well-typed yet still invalid, and code raises it when a value fails a precondition no more specific type describes.
What should you pay attention to when using **TypeError**?+
TypeError signals an operation applied to an object of the wrong type, as in len(5). It usually marks a programming error, so fixing the call is better than catching it; raise it when an argument's type cannot be supported.
How does **KeyError** fit into this lesson?+
KeyError is raised when a mapping lookup names a key that does not exist, and its message is the repr of the missing key. When a missing key is an expected outcome, use dict.get or an in check instead of catching the exception.
Why does `except OSError:` mislead when the condition you can handle is a missing file?+
OSError is the parent of many operating system failures, including PermissionError and disk errors, so the handler runs for situations it was not written for and may report the wrong cause. Catch FileNotFoundError when a missing file is the only case you can handle.