Search code examples
javainitializationclientrmi

How to handle java.rmi.UnknownHostException


I'm working with Eclipse and the code below is the code that I use for RMI initialization.

public void init(String serviceName) throws RemoteException {
    try {
        String host = InetAddress.getLocalHost().getHostName();
        String url = "rmi://"+ host + serviceName;
        Naming.rebind(url,this);
    } catch (UnknownHostException e) { 
        e.printStackTrace();
    } catch (MalformedURLException e) { 
        e.printStackTrace();
    }
}

I'm getting an UnknownHostException.

Since I'm new to this issue, the question may be simple, but I could not handle it.

Thanks in advance.


Solution

  • UnknownHostException means it can't find that host at the network level. There's no handling this type of exception because it means something is broken. I'd print out the URL sent to RMI. It should look something like this:

    //localhost/ServiceImTryingToAccess
    

    If you didn't put a leading "/" on your service it might be:

    //localhostServiceImTryingToAccess
    

    And that certainly would create an UnknownHostException. You really don't need to use InetAddress.getLocalHost() as you could just simply do:

    String url = "//localhost" + serviceName;
    

    Also notice I dropped the rmi:// scheme portion of the URL. It's in the docs that's not needed.

    http://docs.oracle.com/javase/1.4.2/docs/api/java/rmi/Naming.html