liv2hak
liv2hak

Reputation: 15010

socket() - error: variable client might not have been initialized

I have written a very simple client program

import java.net.*;
import java.io.*;

public class GreetingClient
{
   private Socket cSocket;

   public GreetingClient() throws IOException
   {
        String serverName = "127.0.0.1";
        int port = 5063;
        cSocket = new Socket(serverName,port);
   }


   public static void main(String [] args)
   {
      GreetingClient client;
      try
      {
          client = new GreetingClient();
      }
      catch(IOException e)
      {
          e.printStackTrace();
      }

      while (true)
      {
        try
        {
                InputStream inFromServer = client.cSocket.getInputStream();
                DataInputStream in = new DataInputStream(inFromServer);

                System.out.println("Server says " + in.readUTF());
        }
        catch(IOException e)
        {
                e.printStackTrace();
        }
      }
   }
}

When I compile this program I get the error that

GreetingClient.java:33: error: variable client might not have been initialized
            InputStream inFromServer = client.cSocket.getInputStream();
                                       ^
1 error

What does this error mean? if the new Socket() call fails (for e.g if too many sockets are open) then does this mean that I can't use it down in the code? How do I handle situations like this.?

Upvotes: 1

Views: 1423

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 181047

try
{
    client = new GreetingClient();  // Sets client OR throws an exception
}
catch(IOException e)
{
    e.printStackTrace();            // If exception print it
                                    // and continue happily with `client` unset 
}

Later you're using;

// Use `client`, whether set or not.
InputStream inFromServer = client.cSocket.getInputStream();

To fix it, either set client to null where you declare it (which may cause a nullref exception later on use), or don't continue "blindly" after printing the exception (for example, print and return).

Upvotes: 4

Related Questions