1

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

2
  • Does it compile/run? Maybe IDE error. Commented Oct 7, 2010 at 19:17
  • 1
    You don't have your code in any method... Commented Oct 7, 2010 at 19:17

3 Answers 3

9

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.