How to resolve NullPointerExceptions

Discussion in 'Resources' started by masteroftime, Aug 10, 2011.

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


    1. Identify the exact location of the exception: With the error message Java delivers a stack trace showing which methods were called that led to the error, in which files and where the calls occured. Take the uppermost call which is in one of your source files, then you know where exaclty the error occurs.
    2. Identify the variable that causes the exception: The most likely cause of a null pointer exception is that you call a method on an object that is null, so check everything which is before a dot. In the following example you'd have to make sure that myvariable is not null, and that myvariable.getPlayer() is also not null.
      You can check everything with System.out.println()

      If your stack trace shows other methods over your problematic line the cause will probably be that you delivered null to a method which doesn't except null values. So in this case also check the variables you pass as a parameter to the method.
    3. Solve the problem: The solution mostly depends on your plugin but I can give you some general tips:
    • If the null value appears because of a user input make sure to check if the user entered a valid input.
    • If some of your code gives back null when it shouldn't you have to continue the search there.
    • If a system or API function returns null when it shouldn't check if the parameters to this function are correct.
    • If the value comes from a function which is allowed to return null you have to check the result if its null, and only execut the code when the result is not null.
    Hope this is useful for some people.
Thread Status:
Not open for further replies.

Share This Page