Doing something like this at the moment:
try
{
while ((bytesRead = clientStream.Read(data, 0, data.Length)) != 0)
{
string message = Encoding.ASCII.GetString(data, 0, bytesRead) + Environment.NewLine;
txtLog.Invoke(c => c.AppendText(message));
}
}
catch
{
}
Which works but it’s pretty ugly.
I know people are going to say not to catch all exceptions and to at least do something when an exception occurs but I’m writing a server application. If a user abruptly disconnections it doesn’t matter. It doesn’t need to be logged. Also, I never want the program to crash so is catching all exceptions really that bad? The program can still recover. After the while loop this code executes and everything is fine. Right?:
string clientIdentifier = tcpClient.Client.RemoteEndPoint.ToString();
bool clientRemoved = clients.TryRemove(clientIdentifier);
if (clientRemoved)
{
listUsers.Invoke(c => c.Items.Remove(clientIdentifier));
}
tcpClient.Close();
Not really asking a specific question but more of wondering if this is fine and if not, what is a better way to handle a user abruptly disconnecting or any other form of read error?
Catch
IOExceptionand leave the others uncaught (the others indicate bugs in your code, and you don’t want to swallow them). TheException.InnerExceptiontells you what happened, and, if the inner exception is aSocketException, you can check theSocketException.ErrorCodeto get specific detail.Note also that you can check
NetworkStream.CanReadto see if the stream is readable (yes, the user could abruptly close afterNetworkStream.CanReadreturnstruebut before you execute the read). You should still wrap theNetworkStream.Readin atry/catchbut note that you can avoid the exception ifNetworkStream.CanReadis false.