Error Types
Complete reference for Python exception types and error handling. Understanding different error types helps you write more robust code and debug issues effectively.
Built-in Exception Hierarchy
BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
├── StopIteration
├── StopAsyncIteration
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── DeprecationWarning
├── PendingDeprecationWarning
├── RuntimeWarning
├── SyntaxWarning
├── UserWarning
└── FutureWarning
Common Exception Types
Arithmetic Errors
Exception | Cause | Example | Solution |
---|---|---|---|
ZeroDivisionError | Division by zero | 5 / 0 | Check divisor before operation |
OverflowError | Result too large | Large exponential calculations | Use appropriate data types |
FloatingPointError | Floating point operation failed | Platform-specific | Handle with try-except |
Type Errors
Exception | Cause | Example | Solution |
---|---|---|---|
TypeError | Wrong type for operation | "hello" + 5 | Convert types or check types |
AttributeError | Object has no attribute | 5.append(1) | Check object type and available methods |
Value Errors
Exception | Cause | Example | Solution |
---|---|---|---|
ValueError | Correct type, wrong value | int("hello") | Validate input before conversion |
IndexError | Index out of range | [1, 2, 3][5] | Check list length before accessing |
KeyError | Key not found in dictionary | {'a': 1}['b'] | Use get() method or check key existence |
Name and Import Errors
Exception | Cause | Example | Solution |
---|---|---|---|
NameError | Variable not defined | Using undefined_var | Define variable before use |
UnboundLocalError | Local variable referenced before assignment | Local var accessed before assignment | Initialize variable properly |
ImportError | Module import failed | import nonexistent_module | Check module name and installation |
ModuleNotFoundError | Module not found | import missing_module | Install module or check name |
File and OS Errors
Exception | Cause | Example | Solution |
---|---|---|---|
FileNotFoundError | File doesn't exist | Opening non-existent file | Check file existence first |
PermissionError | Access denied | Writing to read-only file | Check file permissions |
IsADirectoryError | Expected file, got directory | Opening directory as file | Verify path is a file |
FileExistsError | File already exists | Creating existing file with 'x' mode | Check existence or use different mode |
Best Practices Summary
- Be specific: Catch specific exceptions rather than using broad
except
clauses - Provide context: Include meaningful error messages and logging
- Don't ignore errors: Avoid empty
except
blocks that hide problems - Use finally for cleanup: Ensure resources are properly released
- Log appropriately: Use proper logging levels and include stack traces when needed
- Fail fast: Validate inputs early and raise exceptions for invalid states
- Document exceptions: Clearly document what exceptions your functions might raise
- Test error paths: Write tests to verify exception handling works correctly
- Use context managers: Prefer
with
statements for resource management - Chain exceptions: Use
raise ... from ...
to preserve error context
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.