Java exception must be caught or declared to be thrown [duplicate]

主宰稳场 提交于 2019-12-25 04:35:18

问题


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:


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.



来源:https://stackoverflow.com/questions/40486405/java-exception-must-be-caught-or-declared-to-be-thrown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!