Search code examples
javasocketsexceptionnetwork-programmingconnection

Java socket reading error exception vs return code


I am reading data off a socket using the following loop

InputStream in = getInputStream();
int retCode;

try {
  while( ( retCode = in.read()) > -1) {
    // do something
  }
  logger.info( "Done reading : Code " + retCode);
} catch( IOException ioe) {
  logger.warning( "IOException while reading : " + ioe.getMessage());
}

Sometimes connection gets dropped, which is expected, but the consequence is inconsistent.
I get an exception, or retCode==-1

Hence my question What determines exception vs return Code when reading a socket?


Solution

  • As @PeterLawrey rightly mentioned

    if in.read() returns -1 - means the end of the stream is reached.

    Exception in case on any unavailability of Stream / communication failure - depends on the Type of Exception thrown.

    More