Network code sometimes throws UnknownHostException

I am trying to get data from a server. Sometimes my code crashes due to UnknownHostException. Why is this? What is the cause of this problem?

+5
source share
4 answers

This can happen if the DNS server fails. Besides increasing the reliability of the DNS server or looking for another one, you can also just use the full IP address instead of the host name. Thus, you do not need to look up an IP address based on the host name. However, I would rather solve the DNS problem and would prefer DNS, as IP addresses may change from time to time.

+4
source

An UnknownHostExceptionindicates that the specified host cannot be translated to an IP address. This may be a problem with your DNS server.

+2

If DNS resolution is interrupted intermittently, catch the exception and try again until you get the name resolution. You can only control what you can control ... And if you cannot control / fix the DNS server, make your application strong enough to handle a fancy DNS server.

+1
source

I also see sporadic UnknownHostException exceptions in Java for no apparent reason. The solution is to simply retry several times. Here is the wrapper for DocumentBuilder.parse that does this:

static Document DocumentBuilder_parse(DocumentBuilder b, String uri) throws SAXException, IOException {
  UnknownHostException lastException = null;
  for (int tries = 0; tries < 2; tries++) {
    try {
      return b.parse(uri);
    } catch (UnknownHostException e) {
      lastException = e;
      System.out.println("Retrying because of: " + e);
      continue;
    }
  }
  throw lastException;
}
0
source

All Articles