- Thread Author
- #1
So I'm finding that with a lot of my code it will work 98% of the time and then after an hour or two it will throw a NullPointers exception. Even if I do a Null check beforehand eg:
So in this snippet there is the odd occassion where the npc is not null and then maybe it gets killed by another player and throws an exception when i try to interact with that npc. Another example is if im looting and the item isn't null when i search the area for it and then when i go to click(); it someone has already picked it up and a NullPointer has been thrown.
Other than using a try catch statement, is there any other good pattern that I could used in any bit of code that might throw a NullPointer?
Code:
LocatableEntityQueryResults<Npc> nearestNpc = Npcs.newQuery().names("Some Npc").results().sortByDistance();
try {
for (Npc npc : nearestNpc) {
if (npc.getTarget() != null) {
if (npc.getTarget().equals(Players.getLocal())) {
if (Players.getLocal().getTarget() != null && Players.getLocal().getTarget().equals(npc)) {
break;
} else {
npc.interact("Attack");
break;
}
}
} else if (Players.getLocal().getTarget() == null) {
getLogger().info("Attacking npc");
if (npc.getAnimationId() != 1190 && npc.getAnimationId() != 1184 && npc.getAnimationId() != 1186) {
npc.interact("Attack");
break;
}
}
}
} catch (NullPointerException e) {
getLogger().warn("Threw null pointer trying to attack");
}
So in this snippet there is the odd occassion where the npc is not null and then maybe it gets killed by another player and throws an exception when i try to interact with that npc. Another example is if im looting and the item isn't null when i search the area for it and then when i go to click(); it someone has already picked it up and a NullPointer has been thrown.
Other than using a try catch statement, is there any other good pattern that I could used in any bit of code that might throw a NullPointer?
Last edited: