Shaunak Amin
Shaunak Amin

Reputation: 181

Python: except EOFError: ... doesn't work

I have a try/except block that sends a message and waits for confirmation from client. If the client terminates, pickle raises an EOFError, but the code below does not catch the error and execute the graceful shut down. It instead prints stack trace. I assume it has to do with the line "except socket.error, EOFError:" - am I using the wrong syntax to handle both socket.error and EOFError there?

        try:
            msgs = [1]
            self.sock.send(pickle.dumps(msgs))
            rdy = pickle.loads(self.sock.recv(2097152))
        except socket.error, EOFError: 
            print 'log socketmanager closing'
            self.terminate()
            break

Upvotes: 0

Views: 9076

Answers (2)

DNS
DNS

Reputation: 38189

In Python 2.x, the form except a, b catches an exception of type a and assign it to a variable called b. In your case this would result in EOFError being ignored. Try this instead:

...
except (socket.error, EOFError):
    ...

Edit: to elaborate, the new syntax in Python 3.0, and available, though not required, in 2.6+, for capturing the value of an exception is except a as b.

Upvotes: 2

Benjamin
Benjamin

Reputation: 11860

break is causing the error, it can only be used inside a for loop or a try/finally block, not try/except, see docs and more.

Upvotes: 0

Related Questions