Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close ServerSocket connection when catching IOException?

Tags:

java

sockets

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!

like image 495
Kirzilla Avatar asked Nov 29 '22 10:11

Kirzilla


1 Answers

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);
        }
    }
}
like image 158
Martijn Courteaux Avatar answered Dec 05 '22 15:12

Martijn Courteaux