简体   繁体   English

关于if(socket!= null)socket.close();

[英]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. 但是我不明白“ if(socket!= null)”的含义。

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. 在最后{try ....块中,我无法理解if(socket!= null)的意思。 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. Thomas是正确的,您不想在空对象上调用socket.close()。

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. 最终块将始终在try块之后执行,无论它们是否无例外地完成所有任务或是否抛出异常。

In the event that the finally block is reached whilst socket is null, you do not need to do anything with the resource. 如果在socket为null的情况下到达了finally块,则无需对资源做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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