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

时间:2015-05-30 08:01:36

标签: 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函数中抛出异常,代码有什么问题?

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

使用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");
}

答案 2 :(得分: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.

答案 3 :(得分:1)

删除pingIP方法的throws并将代码放在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");
    }
}