2013-07-27 28 views
1

我写了一个非常简单的客户端程序插座() - 错误:变量客户端可能没有初始化

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(); 
     } 
     } 
    } 
} 

当我编译这个程序我得到

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

什么错误这个错误的意思?如果新的Socket()调用失败(例如,如果打开了太多的套接字)那么这是否意味着我不能在代码中使用它?我如何处理这样的情况 ?

+0

它意味着它说什么。考虑发生异常时的情况。你在错误的地方有catch块。 – EJP

回答

4
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 
} 

后来你正在使用;

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

要解决它,无论是设置客户端null,你声明它(这可能会导致以后使用nullref除外),或不继续“盲目地”打印异常(例如,打印后返回)。