Skip to content
Advertisement

null pointer Exception after writeObject to OutputStream

This is code for a basic chat server. The user is asked to enter a username and password on the Chat_Client, which is then encrypted using EncryptedMessage’s encrypt method and sent to the Chat_Server via the ClientOutputStream using writeObject.

When code line clientOutputStream.writeObject(uname) is run it is returning a nullPointerException. I am able to output the encrypted username before this line of code but not after. Why is this?

Chat_Client

JavaScript

EncryptedMessage

JavaScript

Error in console

JavaScript

Line 294 in the chat client where the error is pointing to is

JavaScript

Advertisement

Answer

Why is this?

If you get a NullPointerException on that line, there is only one possible explanation. That is that clientOutputStream is null.

The exception is not happening because of the value of uname. The act of passing a null does not and cannot1 throw a NullPointerException. Indeed, it is perfectly valid to write a null to an ObjectOutputStream.

Your next steps should be to:

  1. confirm that clientOutputStream is null at that point and then,

  2. figure out why it is null.

Your code is rather too long for “debugging by visual inspection”, but it looks like that field should be set when you call getConnections() in main(...). Maybe I’m missing something …


1 – There is an edge case where you pass a null instead of a boxed primitive type in a context where the method requires the primitive type. In that case, the unboxing will throw a NullPointerException. That looks like an NPE is being thrown in the the act of making the call, but in fact it is happening in the hidden unboxing operation.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement