1. Introduction
1.绪论
In this tutorial, we’ll learn the cause of UnknownHostException with an example. We’ll also discuss possible ways of preventing and handling the exception.
在本教程中,我们将通过一个例子了解UnknownHostException的原因。我们还将讨论防止和处理该异常的可能方法。
2. When Is the Exception Thrown?
2.异常何时被抛出?
UnknownHostException indicates that the IP address of a hostname could not be determined. It can happen because of a typo in the hostname:
UnknownHostException表示无法确定一个主机名的IP地址。 这可能是因为主机名中的一个错字:。
String hostname = "http://locaihost";
URL url = new URL(hostname);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.getResponseCode();
The above code throws an UnknownHostException since the misspelled locaihost doesn’t point to any IP addresses.
上面的代码抛出了一个UnknownHostException,因为拼错的locaihost没有指向任何IP地址。
Another possible reason for UnknownHostException is DNS propagation delay or DNS misconfiguration.
UnknownHostException的另一个可能原因是DNS传播延迟或DNS配置错误。
It might take up to 48 hours for a new DNS entry to be propagated all around the Internet.
一个新的DNS条目可能需要48小时才能传播到整个互联网。
3. How to Prevent It?
3.如何预防?
Preventing the exception from occurring in the first place is better than handling it afterward. A few tips to prevent the exception are:
首先防止异常的发生要比事后处理要好。防止异常的几个技巧是:。
- Double-check the hostname: Make sure there is no typo, and trim all whitespaces.
- Check the system’s DNS settings: Make sure the DNS server is up and reachable, and if the hostname is new, wait for the DNS server to catch up.
4. How to Handle It?
4.如何处理?
UnknownHostException extends IOException, which is a checked exception. Similar to any other checked exception, we must either throw it or surround it with a try-catch block.
UnknownHostException扩展了IOException,它是一个检查过的异常。与其他检查过的异常类似,我们必须扔掉它或者用try-catch块包围它。
Let’s handle the exception in our example:
让我们来处理我们的例子中的异常。
try {
con.getResponseCode();
} catch (UnknownHostException e) {
con.disconnect();
}
It’s a good practice to close the connection when UnknownHostException occurs. A lot of wasteful open connections can cause the application to run out of memory.
当UnknownHostException发生时,关闭连接是一个好的做法。大量浪费的开放连接会导致应用程序的内存耗尽。
5. Conclusion
5.总结
In this article, we learned what causes UnknownHostException, how to prevent it, and how to handle it.
在这篇文章中,我们了解了导致UnknownHostException的原因,如何防止它,以及如何处理它。
As always, the code is available over on Github.
像往常一样,代码可以在Github上获得。