WHen My code gets some exception like NPE (Null pointer Exception or something else), it prints the trace of where this occurs, some are from my code and some are from open source library because my code uses some open library. My question is: in general, the top of the trace is the final place where such NPE occurs, and the bottom part are the "initial" place where calls starts and it propagates (like one class calls another and so on) upwards until it fails at the top location in the trace , so basically we should fix the top part of the trace, is this idea correct ?
It's the top part that is the immediate cause of the problem, but it may not be the root cause of the problem.
For that you need to look at the first line that is your code.
For example, if I had the following code:
If I get an NPE from that, with a trace something like
then the first place to look is MyClass, on the assumption that the other code works (no guarantee, but 999/1000 it is your code that's wrong).
In this case you shouldn't pass a null String into the doSomething method.
Typically, the top of the trace it good as the first place you should look, yes. However another complication in reading stack traces is that often, one exception causes another exception, and you often need to look after the first stack trace, for a "caused by" followed by another stack trace, and maybe another "caused by" and another stack trace after that.
For example, here's a stack trace:
And here's the code that generated it:
(Note that this is not intended as an example of good coding style or good exception handling - it's just intended to be as short as possible to demonstrate a stack trace with many lines and several "caused by" sections.)
In the code, we see that a calls b which calls c which calls d... moving to the most specific method, k, which actually throws the exception. But where does line k actually appear in the stack trace? You see, it's not at the very first line. Instead, you have to find the last of the "caused by" sections. And then, find the top of the stack trace in that "caused by" section.
Within a single "caused by" section, the logged lines of the stack trace move from most specific to least specific. E.g. from k to j to i to h, indicating that (in reverse order) h called i which called j which called k. But if you compare different caused by sections, the first is the most general, containing the methods that ultimately called the second caused by, which contains the methods that called the third caused by. So, it's like they're in reverse order. If they put the last caused by first, and the first caused by last, then the order would make more sense. But they didn't, so it's good to get used to this ordering - you'll see a lot of it in Java.
Do you want ants? Because that's how you get ants. And a tiny ads: