NoPyGod
NoPyGod

Reputation: 5067

Is it ok to Swallow SocketExceptions in some situations?

Let's say I've programmed an application which connects to a server using the Socket Class (TCP). If I encounter a SocketException while reading or writing, then obviously I have to do go ahead and run a disconnection routine to change the application's state to Disconnected.

But what if I've started to Disconnect, and while I'm cleaning up, a SocketException occurs?

The SocketException doesn't really mean anything to me, as I was going to shutdown the socket myself anyway.. so is it ok to swallow it?

I really want to know what the best practice for this situation is.

Upvotes: 3

Views: 176

Answers (4)

Lex Li
Lex Li

Reputation: 63254

You still need to swallow some, especially when you design a retry mechanism. Right? If you don't swallow the first failure, how can you initialize a second attempt?

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273514

There are situations where an exception is the 'normal' case. If I remember right, in some protocols (SMTP) clients will (can) disconnect when they are ready without sending a proper Close command. On the server side, you then always get an exception that is known to be harmless.

But make sure you only discard the specific exception type at the specific location.

Upvotes: 2

C.Evenhuis
C.Evenhuis

Reputation: 26446

If something goes wrong while disconnecting, then in what state will the socket be? In the worst case, the remote socket will timeout. There really isn't anything you can do to fix that situation.

But as Joe R said, log the message - those exceptions might also occur because Disconnect() is being called twice, which is something you do want to know about. (Edit: don't know if that would cause an exception, but I hope you know what I mean :P)

Upvotes: 0

NibblyPig
NibblyPig

Reputation: 52952

I disregard socket exceptions all the time, both with .net sockets and WCF.

Half the time I send call asynchronously, so if there is a disconnect, I don't find out about it until the timeout is hit, at which time I get a timeout exception that I ignore.

Upvotes: 0

Related Questions