views:

48

answers:

3

What's wrong with this code

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Master
 */
public class Server {
    try
    {
    ServerSocket S = new ServerSocket(3333);
    Socket So = S.accept();
    }
    catch(IOException e)
    {
        System.out.println("IOError");
    }

}

Firstly I wrote the code without try catch and I got an unreported exception java.io.IOException; must be caught or declared to be thrown Error but Netbeans didn't suggest that I add a try-catch block . Now I added the try-catch block manually but It still shows an error and suggests that I must add another try-catch block !

alt text

+9  A: 

You're trying to add a try block at the top level of the class - you can't do that. Try blocks have to be in methods or initializer blocks.

If you really want to create the server socket on construction, put the code in a constructor:

public class Server {

    private ServerSocket serverSocket;
    private Socket firstConnection;

    public Server {
        try
        {
            serverSocket = new ServerSocket(3333);
            firstConnection = serverSocket.accept();
        }
        catch(IOException e)
        {
            System.out.println("IOError");
        }
    }
}

I assume you'll have real exception handling (or rethrowing) rather than just catching the IOException and continuing, of course?

Jon Skeet
oooops i missed that
org.life.java
Yes, of course . TY .
Ahmed
A: 

This is not valid Java. This code needs to be in a block, method, or constructor.

Jacob Tomaw
A: 

From the screenshot of your IDE, the error "must be caught or declared to be thrown" is not the only error you have.

When you have syntax that is this far off, the compiler will likely report several errors, some of which are side-effects of other errors - like not enclosing this code in a method (I'm sure the red X next to the catch block is reporting a similar error).

matt b