开发者

Can I throw exception in a for loop , if memory exceeds in that loop [closed]

开发者 https://www.devze.com 2023-01-19 03:30 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

How开发者_如何学JAVA can I handle an exception happening in a foreach loop?

I want to throw my exception if the for loop didn't work properly.

As data is huge, foreach exits because PHP's memory limit is exceeded.

try
{
 foreach()
}catch (exception $e)

{
echo $e;
}

This is not working. How do I throw an exception?


Memory exceeded is a fatal error, not an exception and cannot be handled with try/catch blocks. What you need is set_error_handler.

EDIT: If that does not work you can use register_shutdown_function as a last resort and check if the script was stopped by and error.


Depending on what happens inside your loop, you can use the memory_get_usage() function. This will not fix any memory related issues, but at least you can prevent PHP from exiting due to exceeding the memory_limit. Example:

try{
   $memory_limit = 1*1024*1024; /* 1M, this should be lower than memory_limit */
   foreach($something as $anything){
      if(memory_get_usage() >= $memory_limit){
          throw new Exception('Memory limit exceeded!');
      }
   }
}
catch(Exception $ex){
   //handle error, optionally freeing memory by unset()-ing unused variables
}


I don't think that is possible. memory exceed is a fatal unrecoverable error. so the page should be terminated when any of this happen.

But I found this question for catch E_ERROR : How do I catch a PHP Fatal Error

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号