异常的"信息"在文化上是独立的吗?

Ray*_*yes 2 .net c# exception-handling

在我正在开发的应用程序中,我需要处理套接字超时与一般套接字异常不同.问题是许多不同的问题导致了a SocketException,我需要知道原因是什么.

没有报告内部异常,因此我需要处理的唯一信息是消息:

"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"
Run Code Online (Sandbox Code Playgroud)

这个问题有一般性和具体的部分:

  1. 基于异常的文本表示来编写条件逻辑是否可以接受?
  2. 有没有办法避免需要异常处理?

下面的示例代码......

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..
    }
}
Run Code Online (Sandbox Code Playgroud)

我想不时地停止"等待新数据",以便我的工作线程可以查看是否已经要求它正常关闭 - 我宁愿避免套接字的跨线程终止来提供这个机制.

And*_*rey 8

当然如此!如果有更多描述性字段SocketException,则不应执行字符串比较.http://msdn.microsoft.com/library/system.net.sockets.socketexception_members.aspx,特别是:

  • 错误代码
  • NativeErrorCode
  • SocketErrorCode