Blog |

How to Handle the Unknown Host Exception in Java

How to Handle the Unknown Host Exception in Java
Table of Contents

The UnknownHostException is an exception in Java that is thrown to indicate that the IP address of a host could not be determined.

Since the UnknownHostException is a checked exception, it either needs to be thrown or surrounded by a try-catch block in code.

 

What Causes UnknownHostException

The UnknownHostException occurs when trying to connect to a remote host using its hostname, but the IP address of the host could not be determined. This usually happens because of a typo in the hostname, or because of a DNS misconfiguration or propagation delay.

 

UnknownHostException Example

Here is an example of an UnknownHostException thrown when trying to connect to an unknown host:

public class UnknownHostExceptionExample {
    public static void main(String[] args) {
        String host = "https://rollbar.co";
        URL url = null;

        try {
            url = new URL(host);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            System.out.println(con.getResponseCode());
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

The above code attempts to connect to a remote host, but has a typo in the hostname. Therefore, running the code throws an UnknownHostException exception:

java.net.UnknownHostException: rollbar.co
    at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
    at java.base/java.net.Socket.connect(Socket.java:648)
    at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:290)
    at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
    at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
    at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
    at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:265)
    at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:372)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:177)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1194)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1082)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:163)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1600)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
    at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:308)
    at UnknownHostExceptionExample.main(UnknownHostExceptionExample.java:14)

 

How to Handle UnknownHostException

Since UnknownHostException is a checked exception, it can be handled by surrounding it with a try-catch block. The earlier example can be updated to handle the exception:

public class UnknownHostExceptionExample {
    public static void main(String[] args) {
        String host = "https://rollbar.co";
        URL url = null;
        HttpURLConnection con = null;

        try {
            url = new URL(host);
            con = (HttpURLConnection) url.openConnection();
            System.out.println(con.getResponseCode());
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (UnknownHostException uhe) {
            uhe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }
}

In the above example, the code that can throw the UnknownHostException is surrounded in a try-catch block. A finally block is also included to close the connection if the UnknownHostException occurs. This is good practice since too many open connections can cause the application to run out of memory.

 

How to Avoid UnknownHostException

The UnknownHostException can be avoided with the following checks:

  • Valid hostname - The hostname should be double checked to make sure it does not contain any typos or whitespaces.
  • DNS settings - The system DNS settings should be checked to ensure that the DNS server is reachable. If the hostname is new, it may take some time for the DNS server to catch up.

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape