I am trying to understand when does it make sense to catch MemoryError
in Python, I got two scenarios:
Scenario 1: MemoryError is successfully caught.
import numpy as np
try:
a = np.ones(100000000000)
except MemoryError:
print 'got memory error, plan B'
a = np.ones(10) # this gets created
Scenario 2: My program freezes
silly = []
c = 0
try:
while True:
silly.append((str(c))) # just increasing the list
c += 1
if c % 1000000 == 0:
print 'counter : {}'.format(c)
except MemoryError:
print 'oops' # never get here
silly.append('silly')
My guess is in the first case, python "knows" how much memory would need to be allocated, and thus raises a MemoryError
exception. While in the second case python does not "know" how big I intent silly
to be. However, list
is a dynamic array; therefore, python should know that extending this array by a certain amount would cause a MemoryError
, why is the exception not raised then?
I have looked at this question, and the relevant paragraph from the docs is:
exception MemoryError
Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (Cās malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause.
Though this helped me, I am still not very clear as to what is going on, and I did not get an exception as the docs seem to indicate.
My questions: Is my guess right on scenario 1? Why is MemoryException
not raised in scenario 2?
I am using Python 2.7.5+, and I am on ubuntu 13.10