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

ExceptionCauseExampleSolution
ZeroDivisionErrorDivision by zero5 / 0Check divisor before operation
OverflowErrorResult too largeLarge exponential calculationsUse appropriate data types
FloatingPointErrorFloating point operation failedPlatform-specificHandle with try-except

Type Errors

ExceptionCauseExampleSolution
TypeErrorWrong type for operation"hello" + 5Convert types or check types
AttributeErrorObject has no attribute5.append(1)Check object type and available methods

Value Errors

ExceptionCauseExampleSolution
ValueErrorCorrect type, wrong valueint("hello")Validate input before conversion
IndexErrorIndex out of range[1, 2, 3][5]Check list length before accessing
KeyErrorKey not found in dictionary{'a': 1}['b']Use get() method or check key existence

Name and Import Errors

ExceptionCauseExampleSolution
NameErrorVariable not definedUsing undefined_varDefine variable before use
UnboundLocalErrorLocal variable referenced before assignmentLocal var accessed before assignmentInitialize variable properly
ImportErrorModule import failedimport nonexistent_moduleCheck module name and installation
ModuleNotFoundErrorModule not foundimport missing_moduleInstall module or check name

File and OS Errors

ExceptionCauseExampleSolution
FileNotFoundErrorFile doesn't existOpening non-existent fileCheck file existence first
PermissionErrorAccess deniedWriting to read-only fileCheck file permissions
IsADirectoryErrorExpected file, got directoryOpening directory as fileVerify path is a file
FileExistsErrorFile already existsCreating existing file with 'x' modeCheck 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?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent