Python Exceptions
An exception type describes a category of failure. Catch the narrowest useful category at a boundary that knows how to respond.
Understand the idea
ValueError often signals an invalid value, TypeError an unsupported type or operation, KeyError an absent mapping key, and IndexError an absent sequence position. OSError covers many operating-system failures with more specific subclasses. Raising a clear application exception can be better than returning an ambiguous magic value from a failed operation.
Where to try it
Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.
A worked example
try:
int("three")
except ValueError as error:
print(type(error).__name__)
Read the result
The output is ValueError. The program handles this specific expected conversion failure.
Try one change
Write separate tests for an invalid numeric value and an absent dictionary key, checking the appropriate exception types.