Java 错误未报告异常IOException;必须被抓住或宣布被抛出

Java Error unreported exception IOException; must be caught or declared to be thrown

我正在制作一个代码,其中该程序向另一台机器发送 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 你不能有 unhandled exceptions。所以你可以这样做:

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
    }
}

使用try-catch块来处理异常:

try{
   pingIP("127.0.0.1");
} catch(IOException e){
    e.printStackTrace();
}

或使用throws

public static void main(String args[]) throws IOException{
    pingIP("127.0.0.1");
}
try{
   pingIP("127.0.0.1");
} catch(IOException e){
    e.printStackTrace();
}

or make it throws in public static void main(String args[])throws IOException.

删除 pingIP 方法的抛出并将代码放在 try catch 块中

试试下面的代码

class NetworkPing
{
    private static boolean pingIP(String host) 
    {
         Boolean b = false;
       try{
            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();
        b = (returnVal == 0)
       }
       catch(IOException e){}
       catch(InterruptedException e){}
       catch(Exception e){}

        return b;

    }
    public static void main(String args[])
    {
        pingIP("127.0.0.1");
    }
}