Java Exception Handling

Java Exception Handling – UnknownHostException

Next up in our comprehensive Java Exception Handling series we’ll be looking over the UnknownHostException. The UnknownHostException can be thrown in a variety of scenarios in which a remote connection fails due to an invalid or unknown host (i.e. IP, URL, URI, etc).

Throughout this article we’ll explore the UnknownHostException in more detail, first looking at where it sits in the overall Java Exception Hierarchy. We’ll then examine some functional code that illustrates how to establish a socket-based client/server connection, and how issues here may result in an unexpected UnknownHostException. Let’s get crackin’!

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Since the UnknownHostException only occurs when dealing with some kind of IO connection, most of our sample code will illustrate a basic example of how to establish a client/server connection. Thus, let’s start by going over the simple Server class:

All the logic occurs within the CreateServer(int port) method, so let’s briefly walk through what’s going on. We start by creating a new ServerSocket instance at the specified port. Then, we create an infinite loop so we can repeat the process over and over as new clients appear. Now we await a new client connection. Once a connection is established, we create an output writer, which sends a specified message to the connected client. Since we want the client to send a message back, we next establish a reader and read from the input stream sent by the client. The sent message is then output to the console, before closing the writer and socket, and repeating the process.

Now, the client side is handled in the Client class:

Just as before, most of the logic takes place in a single method, Connect(String host, int port). Again, we’re starting with an infinite loop so we can maintain our connection the server once established. We start by creating a new Socket to the specified host and port, then create a both a reader and writer. The reader gets the input stream sent from the server and outputs the message. We also give ourselves a few keywords (exit and quit) that can be used to actively disconnect from the server.

Since both the client and server scripts effectively block other threads with infinite loops, we’ll need to establish two different threads to test this. We start by executing the Server class, creating a new server:

Now we launch a new Client instance, which starts with a default connection to localhost:24601. As the client output shows, this works fine:

As intended, the Server recognized the connection and sent a message of "Enter a message for the server.". Now, our client side is awaiting user input in the console, so we’ll enter the sentence, "Are you alive?":

The client output shows that we successfully sent our message to the server. The Server output confirms that the message was received from the Client:

Now, let’s intentionally shut down this connection to localhost:24601 by using the "quit" keyword:

This closes the existing client connection and, per our code, establishes a new connection to localhose:24601:

Notice the slight typo in the host name. We immediately see the output showing an intention to connect, followed by a brief pause and then an expected UnknownHostException is thrown:

As mentioned in the introduction, the UnknownHostException can occur for a variety of reasons, so this is just one example. In this case, the host localhose doesn’t exist, so no connection can be established. Note that this is specifically different from other connection errors where the host simply refuses connections, or hangs and eventually produces a timeout.

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring, Maven, log4j, Struts, Kotlin, Grails, Groovy, and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices!