我正在编写一个代码,其中该程序向另一台机器发送 ping 请求。
import java.io.*;
class NetworkPing
{
private static boolean pingIP(String host) throws IOException, InterruptedException
{
boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");
ProcessBuilder processBuilder = new ProcessBuilder("ping", isWindows? "-n" : "-c", "1", host);
Process proc = processBuilder.start();
int returnVal = proc.waitFor();
return returnVal == 0;
}
public static void main(String args[])
{
pingIP("127.0.0.1");
}
}
在这段代码中,我遇到了这个错误
error: unreported exception IOException; must be caught or declared to be thrown
pingIP("127.0.0.1");
这行显示错误
pingIP("127.0.0.1");
即使我在 pingIP 函数中抛出异常,代码有什么问题?
最佳答案
您的 pingIp
函数抛出异常,因此当您在 main 中调用它时,您必须在那里处理异常,或者从 main 中抛出异常。在 Java 中,您不能有未处理的异常
。所以你可以这样做:
public static void main(String args[]) throws IOException, InterruptedException
{
pingIP("127.0.0.1");
}
或者这个:
public static void main(String args[])
{
try{
pingIP("127.0.0.1");
} catch(IOException ex){
//TODO handle exception
} catch(InterruptedException ex){
//TODO handle exception
}
}
关于Java 错误未报告的异常 IOException;必须被捕获或宣布被抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30543796/