Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions, and how best to retry when a connection is reset?

I have some code which connects to a URL to download a file, and then performs some processing on it. However, sometimes I am receiving the error java.net.SocketException: Connection reset.

I would like to retry to download the file when I receive this error, say a maximum of 3 times before giving up on it. I would like to know what would be the best way to structure this.

Does the following look ok. Does it seem acceptable to place the try-catch block inside of a while loop, or is there a better approach?

All help is much appreciated!

while(!connected && retries > 0) {
  retries--;
  URL downloadUrl;
  URLConnection conn;

  try {
    downloadUrl = new URL(url);
    conn = downloadUrl.openConnection();
    conn.connect();
    connected = true;
    // Perform processing on downloaded file here

  } catch (IOException e) {
    Logger.batchLog(e);
  }
} 
like image 294
QuakerOat Avatar asked Nov 16 '10 19:11

QuakerOat


2 Answers

This is the kind of thing that I'd rather let a bullet-proof connection pool handle for me rather than writing it myself.

like image 113
duffymo Avatar answered Oct 19 '22 08:10

duffymo


I've been wired to think that swallowing an exception is always bad, but I think here, that's the only way to tell if the connection was indeed reset. I guess you are handling the exception according to your requirements, so that's all the matters.

But I would, however, make it so you don't swallow the last exception. If it fails three times, you'll want to rethrow that exception or fail gracefully somehow.

like image 32
shoebox639 Avatar answered Oct 19 '22 10:10

shoebox639