Initialising an object outside of the main method java

Morez :

I’m trying the code below but It doesn’t let me to initialise the socket object outside of the main method. Can someone please explain the problem to me?

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();*/

Why don’t I get the error when I initialise other objects outside main method? Should all the objects be initialised inside main method?

Update: What counfused me is the answer to this question : “Generally, you don't create objects outside of METHODS - main or otherwise. So you CAN create objects outside of main, but inside some OTHER method.”

Why is that a problem?

Jason :

The issue is that the DatagramSocket constructor throws a SocketException so that Throwable must be caught. You cannot catch a Throwable as a class member.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31406&siteId=1