Search code examples
javaexceptionserversocketioexception

ServerSocket.close(). When does it throw an exception?


I've been wondering about this for a long time, and I've obediently been catching any possible exceptions that calling ServerSocket.close() could throw. However, not once have I seen it throwing an exception.

The Javadocs state:

Throws:
    IOException - if an I/O error occurs when closing the socket.

However, as I said, I have never seen it throwing an exception. In what circumstances does an I/O error occur while closing the serversocket? You can assume the code at hand looks like this:

public void terminate() {
    try {
        serverSocket.close();
    } catch (IOException ex) {
        System.err.println(ex.getMessage()); // when and how?
    }
}

I have searched the Internet for an answer, but couldn't come up with anything that would clarify this.


Solution

  • An IOException would be thrown if the socket is already closed when you attempt to close it.