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()調用失敗(例如,如果打開了太多的套接字)那麼這是否意味着我不能在代碼中使用它?我如何處理這樣的情況 ?
它意味着它說什麼。考慮發生異常時的情況。你在錯誤的地方有catch塊。 – EJP