Markus Malkusch's weblog 

yield finally: The exception eater

by Markus Malkusch


Posted on Monday Jun 01, 2015 at 08:43PM in Technology


What do you think will the following code fragment print?

<?php

function generate()
{
    try {
        yield 1;
        yield 2;
    } finally {
        echo "finally\n";
    }
}

foreach (generate() as $i) {
    echo $i, "\n";
    throw new Exception();
}

PHP-5.5 introduced two new language constructs yield and finally. They are not really related to each other, but you could do such nice things as building very easily an iterator which would free its resources guaranteed (e.g. an iterator over an unbuffered query).

In order to demonstrate the execution flow, I created that simple code fragment. This is the output of my PHP-5.6:

1
finally

But this is not what I expected. Something is missing. Do you know what? I will tell you at the very end. So let's see if I did something nasty and check the documentation regarding yield and finally:

If the generator contains (relevant) finally blocks those will be run.

So nothing wrong with my code. Then let's file the bug report and let it run on different PHP versions. And we can finally find the missing stack trace in PHP-5.5:

1
finally

Fatal error: Uncaught exception 'Exception'

Update

I happily see that the bug was fixed within a pleasant short time span in 8405265578d2df8d76be223910b3e44aff4bdfef



No one has commented yet.

Leave a Comment

HTML Syntax: Ausgeschaltet