c#异常未被捕获

时间:2011-01-20 11:40:27

标签: c# exception-handling

我有一个方法,它是TCP客户端的监听器,如下所示:

    private static void ProcessClient(
        Object obj)
    {
        ISession session = (ISession)obj;
        NetworkStream networkStream = null;

        try
        {
            DebugUtility.SetThreadName("Worker: {0}", session.Name);
            networkStream = session.TcpClient.GetStream();
            networkStream.ReadTimeout = Config.ReadTimeout;

            // Loop received packets (blocks untill next packet)
            Int32 packetSize;
            Byte[] buffer = new Byte[session.PacketSize];
            while ((packetSize = networkStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                // Get String from packet  bytes
                String packet = Encoding.UTF8.GetString(buffer, 0, packetSize);

                // Check if packet has data
                if (String.IsNullOrEmpty(packet))
                    continue;

                // Log biggest received package
                DebugUtility.CheckMaxPacketSize(session.Name, packet.Length);

                // Handle packet (in new thread)
                Logger.DebugLog("Received: {0}", packet);
                ThreadPool.QueueUserWorkItem(session.HandlePacket, packet);
            }
        }
        catch (ObjectDisposedException) { }
        catch (NotSupportedException) { }
        catch (TimeoutException) { }
        catch (SocketException) { }
        catch (IOException) { }
        catch (Exception ex)
        {
            Logger.LogException(ex);
        }
        finally
        {
            if (networkStream != null)
                networkStream.Close();

            if (session != null)
                session.Disconnect();
        }
    }

这适用于游戏服务但是当我查看我的日志时,我偶尔会看到这个错误:

System.Int32 Read(Byte[], Int32, Int32): The stream does not support reading.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at BusinessLayer.Listener.ListenerWorker.ProcessClient(Object obj) in C:\path\ListenerWorker.cs:line 141 Line: 0

即上述文件和第141行

        while ((packetSize = networkStream.Read(buffer,....

现在我发现NotSupportedException抛出了这个错误,但为什么会这样呢?为什么它不会被忽略,但它是否会通过正常的Exception ex处理程序?

编辑:有谁知道如何调用此异常?什么时候发生?我只看到它在我的日志中回复给其他用户,但我不知道它什么时候发生。

2 个答案:

答案 0 :(得分:4)

因为NetworkStream.Read投放的是InvalidOperationException,而不是NotSupportedException(与文档相反)。您可以从Reflector确认:

if (!this.CanRead)
{
    throw new InvalidOperationException(SR.GetString("net_writeonlystream"));
}

答案 1 :(得分:0)

永远不会永远吞下异常,除非您100%确定可以对此做些什么并从中恢复。吞下所有异常意味着无论发生什么,您的程序都可以恢复并继续。如果它是OutOfMemoryException或StackOverflowException,你可以编程优雅地处理它们吗?是的记录例外,但为了上帝的爱,重新抛出它并让它完成它的工作:)