简体   繁体   中英

About if(socket != null) socket.close();

While studying network for the first time, I found some examples about sockets. But I can't understand what "if(socket != null)" means.

And.. this is the code.

import java.net.ServerSocket;
import java.net.Socket;

public class MainClass {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(9000);
            socket = serverSocket.accept();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Here it is
                if(socket != null) socket.close();
                if(serverSocket != null) serverSocket.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }
}

in finally { try .... block, I cant understand what if(socket != null) means. does it exists for some unknown exceptions?

(Sorry for my bad english. because I'm not english-native.)

Thomas is correct, you don't want to invoke socket.close() on a null object.

Finally blocks will always execute after a try block, regardless of whether they complete all their tasks without exception or if an exception is thrown.

In the event that the finally block is reached whilst socket is null, you do not need to do anything with the resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM