套接字连接中的Java未报告的异常

时间:2018-08-11 20:33:11

标签: java sockets javac

我正在学习Java,但遇到一个我不明白的奇怪错误,下面是我的代码:

import java.net.Socket;
import java.io.IOException;
class Client{
    public static void main(String[]args){
        System.out.println("Connecting...");
        Socket request=new Socket("127.0.0.1", 1234);
        System.out.println("Connected.");
        request.close();
    }
}

我收到的错误:

test.java:6: error: unreported exception UnknownHostException; must be caught or declared to be thrown
        Socket request=new Socket("127.0.0.1", 1234);
                   ^
1 error

我正在使用javac test.java进行编译,如果有帮助,有人知道如何纠正此错误吗?

3 个答案:

答案 0 :(得分:1)

从文档public Socket(String host, int port) throws UnknownHostException, IOException中引发

UnknownHostException - if the IP address of the host could not be determined.

确保您传递了正确的IP地址

答案 1 :(得分:1)

有两种方法可以实现此目的,您可以在主方法后面写throws UnknownHostException或用try-catch包围它。但是编写IOException而不是odUnknownHostException会更加聪明,因为您仍然需要稍后再实现,并且因为UnknownHostException扩展了IOException,您只需编写throws IOException

方法1:

public static void main(String[]args) throws IOException{
    System.out.println("Connecting...");
    Socket request=new Socket("127.0.0.1", 1234);
    System.out.println("Connected.");
    request.close();
}

方法2:

public static void main(String[]args){
    System.out.println("Connecting...");
    try {
        Socket request=new Socket("127.0.0.1", 1234);
        System.out.println("Connected.");
        request.close();
    } catch (IOException e){
        e.printStackTrace();
    }
}

希望这会有所帮助。 :)

答案 2 :(得分:1)

使用try-with-resources使您不必担心出现问题时关闭内容。如果存在异常,则捕获该异常,然后套接字将自动关闭。

import java.net.Socket;
import java.io.IOException;
class Client{
    public static void main(String[]args){
        System.out.println("Connecting...");
        try (Socket request=new Socket("127.0.0.1", 1234)){
            System.out.println("Connected.");
        } catch (IOException e) {
            System.out.println("Host error:" + e)
        }
    }
}