DanRedux
DanRedux

Reputation: 9359

Looping until a completely reliable exception

Right now I'm doing this:

try:
    while True:
        s = client.recv_into( buff, buff_size )
        roll += buff.decode()

I repeatedly call client.recv_into until it raises an exception. Now, I know eventually, without a doubt, it will raise an exception...

Is there a cleaner way to do this? Is there some sort of loop-until-exception construct or a common way to format this?

Upvotes: 1

Views: 117

Answers (2)

Nils Werner
Nils Werner

Reputation: 36775

There are two ways to do this:

Like you did

try:
    while True:
        s = client.recv_into( buff, buff_size )
        roll += buff.decode()
except YourException:
    pass

or

while True:
    try:
        s = client.recv_into( buff, buff_size )
        roll += buff.decode()
    except YourException:
        break

Personally, I would prefer the second solution as the break keyword makes clear what is happening in case of the exception.

Secondly, you should only catch the exception you're awaiting (in my example YourException). Otherwise IOError, KeyboardInterrupt, SystemExit etc. will also be caught, hiding "real errors" and potentially blocking your program from exiting properly.

Upvotes: 1

dnkywin
dnkywin

Reputation: 1

That appears to be the (pythonic) way to do it. Indeed, the Python itertools page gives the following recipe for iter_except (calls a function func until the desired exception occurs):

def iter_except(func, exception, first=None):
    try:
        if first is not None:
            yield first()
        while 1:
            yield func()
    except exception:
        pass

which is almost exactly what you're done here (although you probably do want to add a except [ExceptionName] line in your try loop, as Nils mentioned).

Upvotes: 0

Related Questions