Python Error Codes
Python Error Codes represent the structured set of exceptions and error signals that Python raises when a program encounters an unexpected situation. Understanding these codes is crucial for advanced developers because they enable precise debugging, robust error handling, and maintainable software design. Errors in Python occur during runtime when the interpreter detects violations of syntax rules, type mismatches, missing resources, or logic faults. They can manifest as built-in exceptions like SyntaxError
, TypeError
, or KeyError
, or as custom exceptions defined by developers to handle application-specific conditions. By learning Python Error Codes, developers can quickly identify the root cause of failures, implement appropriate exception handling strategies using try/except
blocks, and log meaningful diagnostics for production systems. This knowledge is vital in backend software development, where unhandled exceptions can lead to service downtime, data corruption, or security vulnerabilities. In this reference, readers will gain a deep understanding of common Python errors, their triggers, debugging techniques, and best practices for managing exceptions to create resilient and high-quality backend applications.
Consider a backend service that reads user input, processes files, and interacts with a database. Errors like FileNotFoundError
, ValueError
, or ZeroDivisionError
can occur at runtime. Proper error handling ensures the application continues to operate smoothly even when unexpected conditions arise. For instance, a try
block can enclose potentially failing operations, while except
blocks catch specific exceptions. Using multiple except
clauses allows developers to tailor responses to each error type, log diagnostics for debugging, and provide fallback mechanisms. Additionally, combining finally
blocks ensures critical cleanup operations, such as closing file handles or database connections, are executed. This pattern not only prevents crashes but also improves reliability and maintainability. Such practices are essential in real-world backend systems, where robust error management directly impacts system stability, performance, and user trust.
Example
pythondef process_data():
try:
# SyntaxError: intentional wrong syntax (commented to allow execution)
# eval('x === 2')
# NameError
print(undefined_variable)
# ZeroDivisionError
result = 10 / 0
# ValueError
number = int("abc")
# FileNotFoundError
with open("non_existent_file.txt", "r") as f:
content = f.read()
except NameError as ne:
print(f"NameError caught: {ne}")
except ZeroDivisionError as zde:
print(f"ZeroDivisionError caught: {zde}")
except ValueError as ve:
print(f"ValueError caught: {ve}")
except FileNotFoundError as fe:
print(f"FileNotFoundError caught: {fe}")
except Exception as e:
print(f"General exception caught: {e}")
finally:
print("Cleanup operations if needed.")
process_data()
📊 Comprehensive Reference
Error | Description | When It Occurs | Example | Notes |
---|---|---|---|---|
SyntaxError | Occurs when Python code is invalid | Invalid Python syntax | eval('x === 2') |
Compile-time detection |
IndentationError | Occurs when code indentation is incorrect | Wrongly indented block | if True:\nprint("Hi") |
Subclass of SyntaxError |
TabError | Mixing tabs and spaces | Mixed indentation | <tab> <space> print("Hi") |
Rare if consistent indentation is used |
NameError | Variable or function name not defined | Using undefined variable | print(x) |
Often caught early in debugging |
TypeError | Operation on wrong type | Adding int + str | 5 + "5" |
Common in dynamic typing |
ValueError | Invalid value for operation | Converting string to int | int("abc") |
Check input values carefully |
IndexError | Accessing invalid list index | Out-of-range list access | lst = []; lst[1] |
Check lengths before indexing |
KeyError | Accessing missing dictionary key | Nonexistent dict key | d = {}; d['x'] |
Use dict.get() to avoid |
AttributeError | Invalid attribute access | Object has no attribute | [].appendx(1) |
Often typo in method names |
ZeroDivisionError | Division by zero | 10 / 0 |
Check divisors before division | |
ImportError | Module not found | import non_module |
Verify module existence | |
ModuleNotFoundError | Module does not exist | import non_existent_module |
Subclass of ImportError | |
FileNotFoundError | File missing | Opening non-existent file | open("nofile.txt") |
Check file paths |
IsADirectoryError | Expected file, found directory | open("folder") |
OS-specific | |
NotADirectoryError | Expected directory, found file | os.listdir("file.txt") |
OS-specific | |
PermissionError | Lacking OS permissions | File write/read permission denied | open("/root/file") |
Check user privileges |
OSError | OS-level error | General OS failures | os.remove("/root/file") |
Base class for several OS errors |
OverflowError | Number exceeds max size | Large arithmetic result | 2.0**10000 |
Rare in Python 3, big ints allowed |
RecursionError | Exceeded recursion depth | Deep recursion | def f(): f(); f() |
Set limit with sys.setrecursionlimit() |
MemoryError | Out of memory | Large allocations | a = 'a' * 10**10 |
Depends on system memory |
StopIteration | Iterator exhausted | Calling next on exhausted iterator | next(iter([])) |
Used in custom iterators |
AssertionError | Assertion fails | assert False |
Ensure conditions in code | |
FloatingPointError | Floating point issue | Invalid FP operation | numpy.seterr(all='raise') |
Rare, needs numpy FP ops |
UnicodeError | Encoding/decoding fails | "ü".encode("ascii") |
Check encoding schemes | |
UnicodeDecodeError | Decoding fails | b'\xff'.decode('utf-8') |
Common in file read | |
UnicodeEncodeError | Encoding fails | "ü".encode("ascii") |
Check encoding schemes | |
RecursionWarning | Deep recursion warning | import warnings |
Usually not critical | |
DeprecationWarning | Deprecated feature used | Using old functions | warnings.warn("deprecated") |
Helps with migration |
RuntimeWarning | Runtime warning | Potential runtime issues | import warnings |
Not an error |
FutureWarning | Feature will change | warnings.warn("future") |
Plan for upcoming Python changes | |
UserWarning | General warning | warnings.warn("user") |
Custom warning messages | |
PendingDeprecationWarning | Feature may deprecate | warnings.warn("pending") |
Less common | |
ResourceWarning | Resource not released | open("file") |
Python 3 specific | |
ArithmeticError | Generic arithmetic failure | int("x")/0 |
Base class | |
BufferError | Buffer-related error | memoryview(b'').release() |
Rare | |
ConnectionError | Network connection fails | requests.get("bad_url") |
Base for network issues | |
BrokenPipeError | Writing to closed pipe | os.write(fd, b'data') |
Unix-specific | |
ChildProcessError | Child process fails | os.waitpid(-1) |
Rare | |
EOFError | Unexpected EOF | input() EOF |
Occurs with empty input | |
EnvironmentError | Environment problem | OS-level issue | Base for OSError | |
FloatingPointError | Floating-point invalid op | numpy.divide(0,0) |
Rare in standard Python | |
GeneratorExit | Generator close | gen.close() |
Raised inside generator | |
IOError | Input/output operation fails | open("/root/file") |
Merged with OSError in Python 3 | |
InterruptedError | System call interrupted | os.read(fd, 0) |
Unix-specific | |
LookupError | Base lookup error | Invalid lookup | d['x'] |
Base class |
MemoryError | Memory allocation fails | x = 'a'*1e10 |
System dependent | |
NameError | Name undefined | print(x) |
Common typo | |
ReferenceError | Weak reference invalid | import weakref |
Rare | |
RuntimeError | Generic runtime issue | raise RuntimeError() |
Catch-all | |
StopAsyncIteration | Async iterator finished | async for |
Python 3.5+ | |
SyntaxWarning | Syntax questionable | warnings.warn("syntax") |
Does not stop program | |
SystemError | Internal Python error | sys._getframe(0) |
Rare, internal use | |
SystemExit | Exit called | sys.exit() |
Exits program | |
TabError | Mixing tabs and spaces | <tab><space> |
Indentation consistency | |
TimeoutError | Timeout expired | socket.settimeout() |
Network/socket operations | |
TypeError | Wrong type operation | 5 + "5" |
Common dynamic typing error | |
UnboundLocalError | Local variable referenced before assignment | x=1; def f(): print(x); x=2 |
Subclass of NameError | |
ValueError | Invalid value | int("x") |
Check inputs | |
ZeroDivisionError | Division by zero | 10 / 0 |
Already listed |
📊 Complete Properties Reference
Error | Exception Type | Default Behavior | Description | Compatibility |
---|---|---|---|---|
SyntaxError | Exception | Program halts | Occurs for invalid Python syntax | All Python versions |
IndentationError | SyntaxError | Program halts | Incorrect indentation | All Python versions |
TabError | IndentationError | Program halts | Mixing tabs and spaces | All Python versions |
NameError | Exception | Program halts | Undefined variable or function | All Python versions |
TypeError | Exception | Program halts | Invalid operation type | All Python versions |
ValueError | Exception | Program halts | Invalid value for operation | All Python versions |
IndexError | Exception | Program halts | Invalid list index | All Python versions |
KeyError | Exception | Program halts | Missing dictionary key | All Python versions |
AttributeError | Exception | Program halts | Invalid attribute access | All Python versions |
ZeroDivisionError | ArithmeticError | Program halts | Division by zero | All Python versions |
ImportError | Exception | Program halts | Module not found | All Python versions |
ModuleNotFoundError | ImportError | Program halts | Module does not exist | Python 3.6+ |
FileNotFoundError | OSError | Program halts | File missing | Python 3+ |
IsADirectoryError | OSError | Program halts | Expected file, found directory | Python 3+ |
NotADirectoryError | OSError | Program halts | Expected directory, found file | Python 3+ |
PermissionError | OSError | Program halts | Insufficient permissions | Python 3+ |
OSError | Exception | Program halts | OS-level errors | All Python versions |
OverflowError | ArithmeticError | Program halts | Number too large | All Python versions |
RecursionError | RuntimeError | Program halts | Exceeded recursion limit | Python 3+ |
MemoryError | Exception | Program halts | Insufficient memory | All Python versions |
StopIteration | Exception | Program halts | Iterator exhausted | All Python versions |
AssertionError | Exception | Program halts | Failed assertion | All Python versions |
FloatingPointError | ArithmeticError | Program halts | Floating-point operation failed | All Python versions |
UnicodeError | ValueError | Program halts | Encoding/decoding issue | All Python versions |
UnicodeDecodeError | UnicodeError | Program halts | Decoding failure | All Python versions |
UnicodeEncodeError | UnicodeError | Program halts | Encoding failure | All Python versions |
RecursionWarning | Warning | Program continues | Deep recursion warning | All Python versions |
DeprecationWarning | Warning | Program continues | Deprecated feature usage | All Python versions |
RuntimeWarning | Warning | Program continues | Potential runtime issue | All Python versions |
FutureWarning | Warning | Program continues | Feature will change | All Python versions |
UserWarning | Warning | Program continues | General warning | All Python versions |
PendingDeprecationWarning | Warning | Program continues | Feature may be deprecated | All Python versions |
ResourceWarning | Warning | Program continues | Resource not released | Python 3+ |
ArithmeticError | Exception | Program halts | Base for arithmetic failures | All Python versions |
BufferError | Exception | Program halts | Invalid buffer operation | All Python versions |
ConnectionError | OSError | Program halts | Network connection failure | Python 3+ |
BrokenPipeError | OSError | Program halts | Writing to closed pipe | Python 3+ |
ChildProcessError | OSError | Program halts | Child process failure | Python 3+ |
EOFError | Exception | Program halts | Unexpected EOF | All Python versions |
EnvironmentError | OSError | Program halts | Environment problem | Python 3+ |
GeneratorExit | Exception | Program halts | Generator closed | All Python versions |
IOError | OSError | Program halts | Input/output failure | Python 3+ |
InterruptedError | OSError | Program halts | System call interrupted | Python 3+ |
LookupError | Exception | Program halts | Invalid lookup | All Python versions |
ReferenceError | Exception | Program halts | Invalid weak reference | Python 3+ |
RuntimeError | Exception | Program halts | Generic runtime error | All Python versions |
StopAsyncIteration | Exception | Program halts | Async iterator finished | Python 3.5+ |
SyntaxWarning | Warning | Program continues | Suspicious syntax | All Python versions |
SystemError | Exception | Program halts | Internal Python error | All Python versions |
SystemExit | Exception | Exits program | Called by sys.exit() | All Python versions |
TimeoutError | OSError | Program halts | Operation timed out | Python 3+ |
UnboundLocalError | NameError | Program halts | Local variable referenced before assignment | Python 3+ |
ZeroDivisionError | ArithmeticError | Program halts | Division by zero | All Python versions |
🧠 Test Your Knowledge
Test Your Knowledge
Test your understanding of Python Error Codes
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top