Ray Hayes
Ray Hayes

Reputation: 15015

Is the "message" of an exception culturally independent?

In an application I'm developing, I have the need to handle a socket-timeout differently from a general socket exception. The problem is that many different issues result in a SocketException and I need to know what the cause was.

There is no inner exception reported, so the only information I have to work with is the message:

"A connection attempt failed because the connected party did not 
properly respond after a period of time, or established connection 
failed because connected host has failed to respond"

This question has a general and specific part:

  1. is it acceptable to write conditional logic based upon the textual representation of an exception?
  2. Is there a way to avoid needing exception handling?

Example code below...

try 
{
    IPEndPoint endPoint = null; 
    client.Client.ReceiveTimeout = 1000;
    bytes = client.Receive(ref endPoint);
}
catch( SocketException se )
{
    if ( se.Message.Contains("did not properly respond after a period of time") )
    {
        // Handle timeout differently..
    }
}

I'm wanting to cease the "wait for new data" every now and again, so that my worker thread can look to see whether it has been asked to gracefully close - I would rather avoid cross-thread termination of the socket to provide this mechanism.

Upvotes: 2

Views: 147

Answers (2)

chriszero
chriszero

Reputation: 1331

Exceptions are Culture relevant, I have "German" exception messages. Use the SocketErrorCode.

Upvotes: 2

Andrey
Andrey

Reputation: 60065

of course it is! there are more descriptive fields in SocketException, you should not perform string comparison. http://msdn.microsoft.com/library/system.net.sockets.socketexception_members.aspx, especially:

  • ErrorCode
  • NativeErrorCode
  • SocketErrorCode

Upvotes: 8

Related Questions