On Sun, 02 Sep 2012 02:27:02 +0200, Rasmus Lerdorf <ras...@lerdorf.com> wrote:

On 09/01/2012 04:51 PM, Gustavo Lopes wrote

* In fact, if there is a unifying theme in the usage of exceptions in
PHP, is that exceptions are used when OOP interfaces are involved (see
Zend interfaces, SPL, DateTime and PDO -- though optional there). The
core vs. non-core argument only looks attractive because there are few
built-in classes in the core.

I think this is drifting off-topic. Whether or not a generator is an
object is an implementation detail.

My message is certainly on-topic for this thread. But you are right in that correct line of inquiry for the generator error condition is whether an exception/fatal error is appropriate in this situation, not whether exceptions are allowed in the core. For the reasons I explain next, I think it is.

  $things = getStuff();
  foreach($things as $thing) {
    do_some($thing);
  }

which is very normal PHP that you see in millions of lines of code, I
would not expect to have to wrap my foreach in a try/catch here.
[...]

this is still going to fatal on me eventually with an uncaught exception
on the foreach if, for example, I pass the generator a second time to
something and it has run off the end. This is something you don't have
to worry about currently and I think it will cause headaches for people
when they start passing generators around. In theory I should be able to
pass a generator to any existing code that takes an array without having
to worry about modifying that code to catch foreach exceptions. And yes,
I know it is actually a generator exception, but to the average user it
will look like it is foreach throwing.

I think the first thing anyone who uses generators must understand is that they are iterators. They should be compared with iterators, not arrays. With that in mind, the behavior is not surprising for anyone who knows how iterators and foreach interact.

More importantly, there is no other satisfactory solution (except a fatal error). foreach has no return value, so it has no other way to signal a failure. If we used a notice or a warning here what would happen is that code that used generators with an invalid state would, except for the notice, work as if it had been given an empty iterator. Put another way, it would fail with only a notice, and continue. That is a far more serious problem. In other circumstances where we emit warnings, we usually have a return value the caller can check for error conditions.

--
Gustavo Lopes

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to