Java 错误未报告的异常 IOException;必须被捕获或宣布被抛出

标签 java exception ping

我正在编写一个代码,其中该程序向另一台机器发送 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/

相关文章:

Java 大小写切换器

javascript - 如何将错误从 $.ajax 实例冒泡到 $.ajaxSetup?

java - 将异常消息添加到 json 响应

c - 哪一部分导致浮点异常?

java - 从 applet 调用 servlet?

java - 任务 ':app:mergeDebugResources' 执行失败。错误: invalid dimen

java - 如何在不显示的情况下使用 Universal ImageLoader 加载图像

windows - 为什么 ping 在没有管理员权限的情况下也能正常工作?

Linux 上的 PHP Ping 超时不起作用

email - 网站或服务器停机通知工具