Search code examples
javainetaddress

Java: Cannot initialize InetAddress


I can't seem to be able to initialize InetAddress object for some reason, I looked at the documentation and it is exactly as how I use it.

 InetAddress firstMachineAddress = InetAddress.getByName("129.26.70.95");
 InetAddress secondMachineAddress = InetAddress.getByName("129.26.70.108");

And Eclipse says:

Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor

What the heck is wrong?


Solution

  • Your code seems to be in a class's constructor which is extended by another class, like so:

    import java.net.*;
    
    class SuperclassWithUnknownHostException {
        public SuperclassWithUnknownHostException() throws UnknownHostException {
            InetAddress firstMachineAddress = InetAddress.getByName("129.26.70.95");
            InetAddress secondMachineAddress = InetAddress.getByName("129.26.70.108");
        }
    }
    
    class SubclassCannotHandleException extends SuperclassWithUnknownHostException {
    
    }
    

    You need to add a default constructor to the subclass which throws the exception:

    class SubclassCannotHandleException extends SuperclassWithUnknownHostException {
        public SubclassCannotHandleException() throws UnknownHostException {
    
        }
    }