Add NPE check to avoid JVM crash