c# exception not caught
I have a method that is a listener for a TCP client which looks like this:
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();
}
}
This is for a game service but when I check my logs, I occasionally see this error:
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
That is the above described file and line 141 is
while ((packetSize = networkStream.Read(buffer,....
Now I have found that NotSupportedException is throwing this error, but why does it go through? Why is it not ignored but does it fall through the normal Exception ex handler?
Edit: Does anyone know how I can invoke this exception? When does it occur? I only see it coming back in my logs to other users, but I don't know when it happens.
Because NetworkStream.Read
is throwing an InvalidOperationException
, not a NotSupportedException
(contrary to the documentation). You can confirm this from Reflector:
if (!this.CanRead)
{
throw new InvalidOperationException(SR.GetString("net_writeonlystream"));
}
Never ever ever swallow an exception unless you are 100% sure that you can do something about it and recover from it. Swallowing all exceptions implies that whatever happens your program can recover and continue. What if it's an OutOfMemoryException or a StackOverflowException, can you program handle those gracefully? Yes log the exception, but for the love of god, rethrow it and let it do its job :)
精彩评论