我正在尝试下面的代码,但不允许我在main方法之外初始化套接字对象。
有人可以向我解释这个问题吗?

import java.net.DatagramSocket;

public class Server
{
    DatagramSocket socket = new DatagramSocket();
    public static void main(String[] args) {
    Server server = new Server();
    //server.socket = new DatagramSocket(); this is the suggested and working way

    }
}

/*The error is : error: unreported exception SocketException; must be caught or declared to be thrown
    DatagramSocket socket = new DatagramSocket();*/


初始化main方法之外的其他对象时,为什么没有收到错误消息?
是否应该在main方法中初始化所有对象?

更新:
让我感到困惑的是this question的答案:
“通常,您不会在METHODS之外创建对象-main或其他方式。因此,您可以在main之外的其他方法内创建对象。”

为什么会有问题呢?

最佳答案

问题是DatagramSocket构造函数引发SocketException,因此必须捕获Throwable。您不能将Throwable作为班级成员。

10-05 22:48