很抱歉问题,但我完全是Java中的noob。从ServerSocket.close()
抓获IOException
时执行ServerSocket
的最佳做法是什么?根据文档,ServerSocket.close()
抛出IOException
,编译器要求我们抓住它。在IOException
上关闭连接的正确方法是什么?
try {
server = new ServerSocket(this.getServerPort());
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
if (server != null && !server.isClosed()) {
server.close(); //compiler do not allow me to do because I should catch IOExceoption from this method also...
}
}
谢谢!
答案 0 :(得分:7)
如果你打算在try {} catch {}之外关闭ServerSocket,你也可以把它放在finally {}
中。try {
server = new ServerSocket(this.getServerPort());
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
// Do whatever you need to do here, like maybe deal with "socket"?
}
finally {
try {
server.close();
} catch(Exception e) {
// If you really want to know why you can't close the ServerSocket, like whether it's null or not
}
}
答案 1 :(得分:6)
Java中的丑陋。我讨厌它,但这是你应该这样做的方式:把它包装成另一个try-catch:
try {
server = new ServerSocket(this.getServerPort());
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
if (server != null && !server.isClosed()) {
try {
server.close();
} catch (IOException e)
{
e.printStackTrace(System.err);
}
}
}
答案 2 :(得分:4)
在Java SE 7或更高版本中,您可以使用try-with-resources statement,ServerSocket implements java.io.Closeable
,因此在以这种方式使用时,您无需显式#close()
套接字。
try (ServerSocket server = new ServerSocket(this.getServerPort())) {
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
// It's already closed, just print the exception
System.out.println(e);
}
答案 3 :(得分:2)
您可以关闭finally块中的资源
http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html
} finally {
try {
socket.close();
} catch(IOException e) {
e.printStackTrace();
}
}