all Python 3Exceptionsexception
MemoryError
built-in exceptions
Raised when an operation runs out of memory — for example, when building a huge list.
Syntax
raise MemoryError
It rarely means the machine is out of RAM — usually one greedy operation is to blame: a billion-element list, giant string concatenation, reading a huge file in one gulp. The fix is generators and streaming, not an except block. Don't count on catching it either: on Linux with overcommit the kernel tends to kill the process via the OOM killer before Python ever raises anything.
Examples
try:
raise MemoryError
except MemoryError as e:
print(type(e).__name__) # → MemoryError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy