簡體   English   中英

Java客戶端中的NullPointer異常?

[英]NullPointer Exception in a java client?

我正在編寫一個簡單的客戶端,但是我總是在以下位置得到NullPointerException

            while ((input = in.readLine()) != null) {

這是我的代碼:

public class ClientTest {

public static String server = "127.0.0.1";
public static int sport = 11111;
public static int cport = 11111;
private static String clientname="";
public static ExecutorService pool = Executors.newCachedThreadPool();
public static BufferedReader in = null;
public static PrintWriter out = null;
public static Socket socket = null;

public ClientTest(){
    this.clientname="";
}


public static void main(String[] args) {

    try {
        socket = new Socket(server, sport);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch(IOException e) {
        System.out.println("could not create connection:\n" + e);
        try {
            if(socket != null) socket.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    pool.execute(new Communicator());

}

public static class Communicator implements Runnable {
    @Override
    public void run() {
        String input = "";
        try {
            while ((input = in.readLine()) != null) {//here  i get the NPException
                StringTokenizer tokenizer = new StringTokenizer(input);
                tokenizer.nextToken();

                if(input.startsWith("!open")) {
                    if(tokenizer.hasMoreTokens()) System.out.print(tokenizer.nextToken() + "> ");
                    else System.out.print("> ");
                } 
                else if(input.startsWith("!exit")) {
                    System.out.print("Hallo hallo");
                } 
            }
        } catch(IOException e) {
            System.out.println("An error as occurred while reading from server - \n" + e);
        }
    }

}


}

為什么會出現NullPointerException 我仍在初始化String輸入。

我的問題是,為什么我仍然要初始化NP輸入,但為什么會出現NP異常!

如果in為null,那您將得到NullPointerException ……這肯定是可能的。 畢竟,如果main的第一部分中的任何內容引發異常,則將其捕獲,將其打印出來……然后繼續! 因此,如果socket.getOutputStream()引發異常,則inout都將為null。

道德:捕捉異常並像什么都沒發生一樣繼續下去,這很少是一個好主意。

我認為try塊中的某些操作失敗並且in尚未初始化,然后在異常之后運行Comunicator並且in仍然為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM