Built-in Exceptions Reference¶
Comprehensive reference for Python's built-in exceptions.
Exception Hierarchy¶
BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
├── StopIteration
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── FileNotFoundError
│ ├── PermissionError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
├── SyntaxError
│ └── IndentationError
├── SystemError
├── TypeError
├── ValueError
└── Warning
Common Exceptions¶
SyntaxError¶
Raised when Python encounters invalid syntax.
# Invalid syntax
if x = 5: # SyntaxError: invalid syntax
pass
# Caught at parse time, before execution
IndentationError¶
Raised when indentation is incorrect.
NameError¶
Raised when a variable or function name is not found.
TypeError¶
Raised when an operation is applied to an object of inappropriate type.
"hello" + 5 # TypeError: can only concatenate str (not "int") to str
len(5) # TypeError: object of type 'int' has no len()
ValueError¶
Raised when an operation receives an argument of correct type but inappropriate value.
int("abc") # ValueError: invalid literal for int() with base 10: 'abc'
int("10.5") # ValueError: invalid literal for int() with base 10: '10.5'
IndexError¶
Raised when a sequence index is out of range.
KeyError¶
Raised when a dictionary key is not found.
AttributeError¶
Raised when an attribute reference or assignment fails.
FileNotFoundError¶
Raised when a file or directory is requested but doesn't exist.
ZeroDivisionError¶
Raised when division by zero is attempted.
ImportError / ModuleNotFoundError¶
Raised when an import fails.
import nonexistent_module # ModuleNotFoundError: No module named 'nonexistent_module'
from os import nonexistent # ImportError: cannot import name 'nonexistent'
RuntimeError¶
Raised when an error is detected that doesn't fall into any other category.
AssertionError¶
Raised when an assert statement fails.
StopIteration¶
Raised by an iterator to signal that there are no more items.
# Usually handled automatically by for loops
it = iter([1, 2, 3])
next(it) # 1
next(it) # 2
next(it) # 3
next(it) # StopIteration
How to Read Exception Names¶
Exception names follow a pattern:
- Error suffix: Indicates something went wrong (e.g.,
ValueError,TypeError) - Exception suffix: More general (e.g.,
ImportError) - Name structure: Usually describes what went wrong
NameError: A name (variable/function) was not foundTypeError: Wrong type for an operationValueError: Wrong value for an operationIndexError: Index out of rangeKeyError: Dictionary key not found
When to Catch Exceptions¶
Catch Specific Exceptions¶
Catch Multiple Exceptions¶
try:
result = 10 / x
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero")
Catch and Inspect¶
Catch All (Use Sparingly)¶
Finally Block¶
try:
f = open("file.txt")
content = f.read()
except FileNotFoundError:
print("File not found")
finally:
f.close() # Always runs
Best Practices¶
- Catch specific exceptions: Avoid bare
except:orexcept Exception: - Use context managers:
withstatements handle cleanup automatically - Don't catch and ignore: At least log or print the error
- Raise with context: Include the original exception when re-raising
- Use custom exceptions: For application-specific errors, create custom exception classes