0

I am trying to learn Java networking using this manual - http://duta.github.io/writing/StartingNetworking.pdf

Why do I get “must be caught or declared to be thrown” at this line (it is ServerSocket part of the manual). Why the code in the manual is assumed to be working, but mine doesn't?

Socket socket = serverSocket.accept();

Complete code:

public class ChatServer
{
    public static void main(){
       ServerSocket serverSocket = null;
       boolean successful = false;
       int port = 8080;
       try{
        serverSocket = new ServerSocket(port);
        successful = true;
       }catch(IOException e){
           System.err.println("Port " + port + "is busy, try a different one");
       }
       if(successful){
            Socket socket = serverSocket.accept();
            PrintWriter toClient = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String toProcess;
            while((toProcess = fromClient.readLine()) != null)
            {
                if(toProcess.equalsIgnoreCase("Stop"))
                    break;
            String processed = "Echo: " + toProcess;
            toClient.println(processed);
            }
            toClient.close();
            fromClient.close();
            socket.close();
            serverSocket.close();
       }

  }
} 
  • 1
    Have a look at the definition of `main()` in the tutorial. You'll notice a `throws Exception` which is missing in your code. Btw, if you have problems handling exceptions or understanding them starting with client-server applications is probably skipping a few steps ahead, i.e. you might want to start learning the basics first. – Thomas Nov 08 '16 at 12:03

1 Answers1

2

Checked exceptions must be either caught or declared. Unchecked exceptions (RuntimeException or any of its children) do NOT have to be caught or declared.

Your call to serverSocket.accept() could throw a checked exception. See its signature, it says "throws ...Exception" This you either have to catch using a catch block or declare, like it's done on the accept() method.

Jeroen van Dijk-Jun
  • 1,028
  • 10
  • 22