Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
216 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...