python程序memory error_如何处理“ MemoryError”?用Python代码

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值