2013-07-27 111 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除外),或不繼續「盲目地」打印異常(例如,打印後返回)。

相關問題