MemoryError — Easy Examples
Raised when an operation runs out of memory
Triggering MemoryError
How MemoryError is raised and how to catch it.
python
# Triggering and catching MemoryError try: raise MemoryError("simulated memory error") except MemoryError as e: print(f"Caught MemoryError: {e}") print(f"Type: {type(e).__name__}")
MemoryError is raised when raised when an operation runs out of memory. Always catch specific exceptions rather than bare except clauses.
Handling MemoryError
Basic error handling pattern for MemoryError.
python
# Safe handling pattern def safe_operation(): try: raise MemoryError("simulated memory error") except MemoryError: print("Operation failed gracefully") return None result = safe_operation() print(f"Result: {result}")
Wrapping risky operations in try/except blocks prevents your program from crashing.
Want to try these examples interactively?
Open Easy Playground