I have some piece of python code which generates a MemoryError after a while. I know that it consumes a lot of memory.
So, I decided to put the code within a try/except block so that the skeleton looks like the following:
while True:
while True:
try:
#---- do some stuff
except MemoryError as err:
print(err)
break
So, my idea is to break out of the first while-loop if a MemoryError occurs and since I have an outer while-loop, it will start the program again.
It seems that it works for the moment but I am not sure. After a while, it stops again and I need to restart the program again.
Does somebody know a better solution so that the program can run after the MemoryError again?
解决方案
It is hard to assess what to do without knowing what do you do inside this try but I will try.
Frstrly, regarding continuing the try-except block. I am afraid you cannot do this.
So short answer is: you cannot go back to try block to place where exception occured, you can go to first line of try
What you can do:
I usually handle my exceptions like the following. Create while True loop as such:
while True:
try:
#some code here
except SomeException:
continue
Now you can continue to try after exception occured.
Second way (but not reccomended) is to embedd your code using some function and recursively execute it.
def foo():
try:
while True:
foo2()
except StopIteration:
#end code
def foo2():
while True:
try:
#some code here
except MemoryError:
foo2()
raise StopIteration()
However this is very DANGEROUS however if your memory is being exceeded not many times (<1000) this can be okay way to go if you need to do something before while True however you need to watch solution closely.