views:

189

answers:

3

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?

+6  A: 

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.

BalusC
(Re: 3., C++ allows you to omit unused parameter names. Java does not.)
Tom Hawtin - tackline
A: 

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"

Peter Lawrey
+1  A: 

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

EJP