문제

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.

  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).

  2. What is the difference between the "System.err.println" and "System.println"?

  3. 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"

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top