我想要获取 InetAddress 的实例,但不想像该类的每个工厂方法那样放在 try-catch 中:
InetAddress addr = InetAddress.getByAddress(ipAddr);
有没有一种方式可以从字符串 IP 实例化 InetAddress,而不会抛出任何已检查的异常?
我想要获取 InetAddress 的实例,但不想像该类的每个工厂方法那样放在 try-catch 中:
InetAddress addr = InetAddress.getByAddress(ipAddr);
InetAddress.getByAddress(...)
会抛出UnknownHostException
,这是一个受检异常,因为它是Exception
的子类。您必须通过捕获或自行抛出每个受检异常来处理它们。没有其他方法。在您的代码中的某个地方,您将不得不捕获它,否则您的程序将崩溃。只有两种处理方法。 第一种是将其放入try-catch块中,但您希望避免这种情况,另一种方法是使用throws关键字将此异常进一步抛出:
public static static void main(String[] args){
try {
method();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void method() throws UnknownHostException {
InetAddress addr = InetAddress.getByAddress(null);
}
当你使用try-catch调用这个方法时进行处理