def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like __builtin__.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Examples:
        bsddbiter = iter_except(db.next, bsddb.error, db.first)
        heapiter = iter_except(functools.partial(heappop, h), IndexError)
        dictiter = iter_except(d.popitem, KeyError)
        dequeiter = iter_except(d.popleft, IndexError)
        queueiter = iter_except(q.get_nowait, Queue.Empty)
        setiter = iter_except(s.pop, KeyError)
    
    >>> s = {1, 2, 3}
    >>> setiter = iter_except(s.pop, KeyError)
    >>> sorted(setiter)
    [1, 2, 3]
    >>> len(s)
    0
    
    >>> d = {1: 2}
    >>> dictiter = iter_except(d.popitem, KeyError, lambda: 'init')
    >>> list(dictiter)
    ['init', (1, 2)]
    """
    try:
        if first is not None:
            yield first()
        while 1:
            yield func()
    except exception:
        pass
