PEP 342 (Coroutines via Enhanced Generators) added a throw()
method to generator objects, which allows the caller to raise an exception inside the generato
In my opinion the throw()
method is useful for many reasons.
Symmetry: there is no strong reason for which an exceptional condition should be handled only in the caller and not also in the generator function. (Suppose that a generator reading values from a database returns a bad value, and suppose that only the caller knows that the value is bad. With the throw()
method the caller can signal to the generator that there is an abnormal situation that has to be corrected.) If the generator can raise an exception, intercepted by the caller, the reverse should also be possible.
Flexibility: a generator function may have more than one yield
statement, and the caller may not be aware of the internal state of the generator. By throwing exceptions it is possible to reset the generator to a known state, or to implement more sophisticated flow control which would be way more cumbersome with next()
, send()
, close()
alone.
Asking for use cases may be misleading: for every use case you could produce a counter example without the need for a throw()
method, and the discussion would continue forever...