我正在尝试使用本手册学习Java网络 - http://duta.github.io/writing/StartingNetworking.pdf
为什么我会在这一行得到“必须被捕获或声明被抛出”(这是手册的ServerSocket部分)。为什么假设手册中的代码有效,但我的代码没有?
Socket socket = serverSocket.accept();
完整代码:
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();
}
}
}
答案 0 :(得分:2)
必须捕获或声明已检查的异常。
,无需捕获或声明未经检查的异常(RuntimeException或其任何子代)您对serverSocket.accept()的调用可能会抛出一个已检查的异常。看到它的签名,它说"抛出...异常"你要么必须使用catch块或声明,就像在accept()方法上完成一样。