Search code examples
javanullpointerexceptioncollision

Why am I getting this error only sometimes?


Basically, I am have a basic method for collision detection, and sometimes when I run the applet, it works, but most of the time it doest. Here is the error and some code:

Exception in thread "Thread-3" java.lang.NullPointerException
at zombies.Main.checkCollision(Main.java:110)
at zombies.Main.run(Main.java:140)
at java.lang.Thread.run(Unknown Source)

    public void checkCollision(){
    if(player.playerRect.intersects(platform.platformRect)){ // line 110

        player.dy = 0;
        player.y = (platform.y - player.height);
        player.isTouching = true;
    }

....

    @Override
public void run() {
    try {
        while(true){

        checkCollision(); // line 140
        player.move();

        Thread.sleep(15);

Any help is greatly appreciated! Thanks in advance!


Solution

  • The answer is that either player, player.playerRect or platform is null.

    You would need to break them out into separate checks to figure out exactly which one is null (or stop there with a breakpoint in a debugger).

    To separate out the checks, your code would look something like this:

    if (player == null) {
        throw new NullPointerException("player is null");
    }
    if (player.playerRect == null) {
        throw new NullPointerException("player.playerRect is null");
    }
    if (platform == null) {
        throw new NullPointerException("platform is null");
    }
    

    This will allow you to look at the exception to determine which object is null. You can then examine your code to find out why that object is sometimes set to null, and fix that situation.

    Alternatively, instead of throwing NullPointerExceptions, you can bypass that portion of the code, since maybe it is valid for the object to be null.

    That said, if you are dealing with multiple threads, and the problem only occurs sometimes, you should probably look in to Java's locking, synchronization and other concurrency tools. Otherwise you might run into a situation where one thread checks to see if an object is null, but after that comparison and before it has a chance to act on the result, another thread alters the object.

    Imagine this sequence of events:

    • Thread A checks and finds that player is not null
    • Thread B runs and replaces player with a null
    • Thread thread A runs, thinking that player is not null, tries to access its playerRect member, but since it is now null, it a NullPointerException is thrown