I am trying to data from a server. Sometimes my code fails due to an UnknownHostException
. Why is that? What is the cause of this problem?
An UnknownHostException
indicates the host specified couldn't be translated to an IP address. It could very well be a problem with your DNS server.
This may occur if a hiccup in DNS server has occurred. Apart from making the DNS server more robust or looking for another one, you can also just use the full IP address instead of the hostname. This way it doesn't need to lookup the IP address based on the hostname. However, I would rather fix the DNS issue and prefer the DNS since IP addresses may change from time to time.
If the DNS resolution fails intermittently, catch the exception and try again until you get name resolution. You can only control, what you can control... And if you can't control/fix the DNS server, make your app robust enough to handle the quirky DNS server.
I too am seeing sporadic UnknownHostExceptions in Java for no apparent reason. The solution is just to retry a few times. Here is a 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;
}