Java:无法初始化InetAddress

时间:2016-10-27 10:57:57

标签: java inetaddress

由于某些原因,我似乎无法初始化InetAddress对象,我查看了文档,这与我如何使用它完全一样。

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

Eclipse说:

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

到底出了什么问题?

3 个答案:

答案 0 :(得分:1)

您的代码似乎位于类的构造函数中,该构造函数由另一个类扩展,如下所示:

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 {

}

您需要向抛出异常的子类添加默认构造函数:

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

    }
}

答案 1 :(得分:0)

您是否正在处理所调用方法引发的ALTER TABLE tsurphus_2016 CHANGE `tsurphus_2015id` `tsurphus_2016id` INT( 11 ) NOT NULL AUTO_INCREMENT

UnknownHostException

答案 2 :(得分:0)

inetAddress对象会抛出一个异常,因此您需要在其周围包装try-catch或让您的方法也抛出异常。此外,我相信你收到错误,因为有一个例外,你没有处理。 getByName()方法使用webaddress名称的字符串参数,如www.google.com或www.amazon.com等。

try{
        InetAddress Address = InetAddress.getByName("www.google.com"); 
        System.out.println(Address);
    }catch(UnknownHostException e){
        e.printStackTrace();
    }

显示www.google.com/64.233.177.147