Can I have IO exception when I create a server socket in Java?
I have the following code:
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
The code is taken from a java.sun.com.
I have several questions concerning the above given short part of the code.
Why do we want to catch an IOException. I though that IOException is something that can happen when we use input-output methods (not networking methods).
W开发者_开发知识库hat is the difference between the "System.err.println" and "System.println"?
In the catch statement we have "e". What for? Do we use it latter?
1: Why do we want to catch an IOException. I though that IOException is something that can happen when we use input-output methods (not networking methods).
Networking is also input/output. Byte streams through a socket.
2: What is the difference between the "System.err.println" and "System.println"?
The first writes to stderr, the second doesn't exist.
3: In the catch statement we have "e". What for? Do we use it latter?
To have a reference to the exception so that you can if necessary log or rethrow it.
(a) You aren't 'creating a server socket' in this code, you are accepting a Socket from a ServerSocket.
(b) That can fail for a lot of reasons including closure of the ServerSocket; running out of FDs; network stack problems; memory exhaustion; ... so it throws IOException.
One common reason for accept to throw an IOException is running out of file handles. It need two file handles to create the socket and if you run out you get an error like "Too many files open"
精彩评论