Skip to content
Advertisement

Can an assignment statement cause a null-pointer exception?

This code snippet is reading camera picture Exif metadata using ExifInterface: Apparently, one particular picture has no or invalid datetime and .getDateTime() is returning null. In the code I assign it to a long, dt, and that results in the exception that is shown below. Of course, if I un-comment the null-check just prior to the assignment, all is well.

So, I have 1 question and 1 lesson:

  1. I’m assuming getDateTime() is really the culprit. Can an assignment cause such a exception?

  2. As you see, the offending line is within try/catch but it wasn’t catching it because I was catching only IOException. When it was changed to Exception, it caught.

    JavaScript
JavaScript

Advertisement

Answer

It seems exifInterface.getDateTime() returns a Long, and in this case, it returns null. You assign it to long dt which involves an unboxing operation. The compiler emits code to convert the Long to a long by calling longValue() on it, which throws the NPE. You can see it in your stack trace:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘long java.lang.Long.longValue()’ on a null object reference

Even if you were to assign it to a Long first:

JavaScript

it would still have to unbox it, and thus, yes, an assignment can throw a NullPointerException.

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