0

So, I have a this ObjectInputStream which most of the time will be null. (It is for a chat server.) I thought this code would take care of null conditions. (This is in it's own thread so that it doesn't block the rest of the program. The previous solution that I am rewriting to send objects, not strings, used to block until it got something. I am looking for a way to have similar behavior.)

When the program runs, I get a null pointer exception here. (Because the value is null obviously!) How can I get the stream to wait until it receives something to try and read it? (or to keep trying until it gets something that isn't null?).

     while((message = (Message)JavaChat.connection.oInStream.readObject()) != null)
     {
         // ...do some stuff...
     }

EDIT: Stack trace. (Seems a little short no?)

java.lang.NullPointerException
    at javachat2.IncomingReader.run(IncomingReader.java:33)
    at java.lang.Thread.run(Thread.java:745)

Am I missing something obvious here?

Bassinator
  • 1,682
  • 3
  • 23
  • 50

1 Answers1

2

Assuming that the exception is thrown in this line:

while((message = (Message) JavaChat.connection.oInStream.readObject()) != null)

there are 3 and only 3 possible causes.

  1. JavaChat is a variable or constant and it is null. (Unlikely, as it would be a huge Java style violation for JavaChat to be anything other than a class name.)

  2. The value of JavaChat.connection is null.

  3. The value of JavaChat.connection.oInStream is null.

There is insufficient information in your Question to distinguish these causes. Your next step should be to carefully examine your source code to see which of those explanations is possible in the context of your program. If that (and some logic!) doesn't help, then either use a debugger or trace prints to determine which of those values is null.

Once you've found the null work backwards to where it came from ... and why.


The best way to debug programs is by understanding the source code and applying logical deduction.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216