Null exception while checking if variable is null

Discussion in 'Plugin Development' started by kacpicygan123, Jan 27, 2022.

Thread Status:
Not open for further replies.
  1. Offline

    kacpicygan123

    Message "Check" is displayed but I receive a message about nullpointer exception in console in the line with if statement. Code is executed in BukkitRunnable. Why does it throw exceptions?
    Code:
    for (ItemStack is : player.getInventory().getContents()) {                        
            if (is.getType() != null && is != null) {  //exception thrown
                 player.sendMessage("Check");
     }
     else {
           continue;
    }
    }
    
    
    Code:
    
    Error:
    [01:26:27] [Server thread/WARN]: [FirstPlugin] Task #2 for FirstPlugin v0.1 generated an exception
    java.lang.NullPointerException: null
            at runnables.ItemChecker$1.run(ItemChecker.java:46) ~[?:?]
            at org.bukkit.craftbukkit.v1_16_R1.scheduler.CraftTask.run(CraftTask.java:81) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at org.bukkit.craftbukkit.v1_16_R1.scheduler.CraftScheduler.mainThreadHeartbeat(CraftScheduler.java:400) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at net.minecraft.server.v1_16_R1.MinecraftServer.b(MinecraftServer.java:1061) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at net.minecraft.server.v1_16_R1.DedicatedServer.b(DedicatedServer.java:354) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at net.minecraft.server.v1_16_R1.MinecraftServer.a(MinecraftServer.java:1009) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at net.minecraft.server.v1_16_R1.MinecraftServer.v(MinecraftServer.java:848) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at net.minecraft.server.v1_16_R1.MinecraftServer.lambda$0(MinecraftServer.java:164) ~[spigot.jar:git-Spigot-0287a20-7560f5f]
            at java.lang.Thread.run(Thread.java:834) [?:?]
    
     
  2. Offline

    timtower Administrator Administrator Moderator

    @kacpicygan123 Do the is != null check before you start using it with getType
     
    Strahan likes this.
  3. Offline

    Strahan

    Yea, remember, things are evaluated from left to right just like you read. So you are asking the JVM to first check if is.getType() is null, then you're telling it if so now check if is is null. I'm sure you can see the issue there, heh.
     
Thread Status:
Not open for further replies.

Share This Page