5

Sorry for question, but I'm totally noob in Java. What is the best practice to execute ServerSocket.close() when caught IOException from ServerSocket? According to docs, ServerSocket.close() throws IOException and compiler asks us to catch it. What is the proper way to close connection on 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...
    }
}

Thank you!

Kirzilla
  • 16,368
  • 26
  • 84
  • 129

4 Answers4

8

That's ugly in Java. I hate it, but this is the way you should do it: Wrapping it into another 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);
        }
    }
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
8

If you are going to close the ServerSocket outside of the try{}catch{} anyways, you may as well put it in a 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
    }
}
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
7

In Java SE 7 or later you can use try-with-resources statement, ServerSocket implements java.io.Closeable, so you don't need to explicitly #close() the socket when used in this way.

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);
}
Leif Gruenwoldt
  • 13,561
  • 5
  • 60
  • 64
2

You can close the resources in the finally block,

http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html

 } finally {
      try {
        socket.close();
      } catch(IOException e) {
         e.printStackTrace(); 
      }
}
r0ast3d
  • 2,639
  • 1
  • 14
  • 18