How to troubleshoot NullPointerException?

前端 未结 3 427
太阳男子
太阳男子 2020-12-22 11:40

The below program throws a NullPointerException. In Log cat it shows:

01-09 20:40:34.366: D/RemoteIt(2809): java.lang.NullPointerException

相关标签:
3条回答
  • 2020-12-22 12:22

    First, trouble-shooting Exceptions is called Debugging. Second, there are several way to debug.

    1.

    For starts, you should find out what line is causing the exception. You can do this by looking at the topmost line of the stack trace. If this is not a reference to code you wrote, check the next line, then the next, etc - until you find something you wrote. If you do not find such a line, skip to step 3.

    2.

    Once the line is found, add several print statements before the line to print the current variables. For example:

    Log.d("DEBUG", "myVariable = " + myVariable == null ? "null" : myVariable);
    

    Then run it and check the output.

    3.

    The final step is to use the Eclipse Debugger. If you know the line where the code breaks, add a breakpoint by left clicking on the line number. If not, just add the breakpoint on the first line of onCreate. The link above tells how to use this feature in detail.

    Also remember that Android is shipped with many debug tools. You can read about them here.

    0 讨论(0)
  • 2020-12-22 12:31

    Your question, as stated, asks about how to troubleshoot this.

    You need to figure out what's null on the line throwing the Exception. To do that, you take a look at the stack trace to see which line is causing the problem. Then you either step through your program with a debugger (or a piece of paper and a pencil) or just add print statements to figure out which variable is null.

    When you know which variable is null, you can trace back through the program to figure out why it's null. When you know why it's null, you can fix your problem.

    0 讨论(0)
  • 2020-12-22 12:44

    The key problem is what you're doing in your catch clause. Simply change the Log.d to exception.printStackTraceprintStackTrace() and that will give you more information about the line causing your issue.

    0 讨论(0)
提交回复
热议问题