I have a function to request an update from the server. I provide the query and also indicate the expected length of the response.     public Byte[] GetUpdate(Byte[] query, int expLength)    {        var response = new Byte[expLength];        lock(Client)        {            Stream s = Client.GetStream();            s.Write(query, 0, query.Length);            var totalBytesRead = 0;            var numAttempts = 0;            while(totalBytesRead < expLength && numAttempts < MAX_RETRIES)            {                numAttempts++;                int bytes;                try                {                    bytes = s.Read(response, totalBytesRead, expLength);                }                catch (Exception ex)                {                    throw new IOException();                    }                totalBytesRead += bytes;            }            if(totalBytesRead < expLength)            {                // should probably throw something here                throw new IOException();            }        }        return response;    }I don't like the way I have written this code esp with two exception throwing. Is there a more elegant way to write the code?
Reading data from network stream
c#;io;networking
You should never throw an empty exception. Imagine someone uses your code and receives an empty IOException. What happened? How do you debug this?First, you need a message that explains the situation. Second, you should use this constructor : IOException(String,Exception). This way, the exception you throw will contain the real exception, the one that causes problem. This will help debugging your code.if(totalBytesRead < expLength){    // should probably throw something here    throw new IOException();}Yeah, you probably should throw something.. meaningful! Once again, add some information in there. Think about the poor soul that would need to debug this later.I don't think it's a bad thing to throw exceptions in two separate places, but it's a bad thing to throw meaningless exceptions (I hope the message is clear ahah)