I'm parsing a XML file with Commons Digester and I don't understand what's wrong in my code: I'm stuck with this java.lang.NullPointerException.
THis is the code: http://pastie.org/1708374
and this is the exception: http://pastie.org/1708371
I guess it is a stupid error
thanks
Well, this is the problem:
if (centroids.length == 0)
You're never assigning a value to centroids as far as I can see, so it will always be null. Then when you try to dereference it in the line above, it will throw NullPointerException.
The first that the next line of code tried to use centroids[0] suggests that you don't really understand Java arrays. Perhaps you really wanted a List of some description?
I would also strongly suggest that instead of a Map<String, String> which always has the same five keys, you create a type (e.g. Centroid) which has the properties title, description, tags, time, and event. Then you can just make centroids a List<Centroid>:
List<Centroid> centroids = new ArrayList<Centroid>();
then when you get some data...
Centroid centroid = new Centroid(...);
centroids.add(centroid);
Oh, and you're also currently using == to compare strings... don't do that: use equals, as otherwise you'll be comparing string references.
As a general note on how to read a NPE stacktrace:
When you get an exception stack trace, look at the Caused by line and the first line after it
Caused by: java.lang.NullPointerException
at CentroidGenerator.nextItem2(CentroidGenerator.java:31)
A null pointer exception most often occurs when you try to invoke a method on an object and that object is null.
The error message above tells you that the error occurs on line 31 of CentroidGenerator.java:
if (centroids.length == 0) {
Method invokation is of the format object.method, so you know that in this instance the object that is null is centroids.
A quick visual way to determine what's null is to just look at what's on the left of dots on the line where the exception occurs. In lines where you have multiple method calls, you don't immediately know what object is null and you may need some more exploration, but not in this instance.
To fix the problem, refer to Jon's answer.
Related
I'm building an inverted index and currently getting a null pointer exception in reduce when using context.write. Can anyone spot why? I presume something to do with serialising as I've never done that before? The error also happens when I print out h.
Two things that I can spot directly regarding the serialization without a stacktrace:
HMapValue needs a default constructor, it can't be created by Hadoop without one
In the default constructor you need to initialize the ArrayListWritable correctly (not null and it needs the setClass method to deserialize correctly.
Turns out it was because I had iterated over the data set twice (the line int df = Iterables.size(values); tricked me). The iterator hadn't reset hence the main block of reduce didnt run and finally I hit a null pointer because I tried accessing my data that hadn't even initialised.
After checking the JavaDocs for a method I was thinking of using, requiredNonNull, I stumbled across the first one with the single parameter (T obj).
However what is the actual purpose of this particular method with this signature? All it simply does is throw and NPE which I'm somewhat positive (as a I may be missing something obvious here) would be thrown anyway.
Throws:
NullPointerException - if obj is null
The latter actually makes sense in terms of debugging certain code, as the doc also states, it's primarily designed for parameter validation
public static <T> T requireNonNull(T obj,String message)
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Therefore I can print specific information along with the NPE to make debugging a hell of a lot easier.
With this in mind I highly doubt I would come across a situation where I'd rather just use the former instead. Please do enlighten me.
tl;dr - Why would you ever use the overload which doesn't take a message.
A good principle when writing software is to catch errors as early as possible. The quicker you notice, for example, a bad value such as null being passed to a method, the easier it is to find out the cause and fix the problem.
If you pass null to a method that is not supposed to receive null, a NullPointerException will probably happen somewhere, as you already noticed. However, the exception might not happen until a few methods further down, and when it happens somewhere deep down, it will be more difficult to find the exact source of the error.
So, it's better when methods check their arguments up front and throw an exception as soon as they find an invalid value such as null.
edit - About the one-parameter version: even though you won't provide an error message, checking arguments and throwing an exception early will be more useful than letting the null pass down until an exception happens somewhere deeper down. The stack trace will point to the line where you used Objects.requireNonNull(...) and it should be obvious to you as a developer that that means you're not supposed to pass null. When you let a NullPointerException happen implicitly you don't know if the original programmer had the intent that the variable should not be null.
It is a utility method. Just a shortcut! (shortcut designers have their ways of doing their shortcut style).
Why throwing in the first place?
Security and Debugging.
Security: to not allow any illegal value in a sensitive place. (makes inner algorithm more sure about what are they doing and what are they having).
Debugging: for the program to die fast when something unexpected happens.
I have a peace of code that is poorly written, like so:
HashMap<String, TceFile> mapPresetLastKdf = new HashMap<String, TceFile>( (HashMap<String, TceFile>) RsessionVars.get( sessionVars, Constants.SVAR_ENC_PRESET_LAST_KDF_MAP ) );
HashMap<String, String> mapPresetApid = new HashMap<String, String >( (HashMap<String, String >) RsessionVars.get( sessionVars, Constants.SVAR_ENC_PRESET_APID_MAP ) );
Clearly, first line fails if RsessionVars.get returns null. In that case second line is never executed.
However, Eclips IDE does not signal this failure to me, it continues executing as all is OK.
I am affraid I have many places in the code like this one. How can I detect those?
How can I force Eclipse to stop and report error on lines like this?
Edit:
This seems to be problem with exception handling.
HashMap<String, TceFile> mymap = new HashMap<String, TceFile>( null );
This should report null pointer exception.
Why is this exception not visible anywhere?
There's a difference between an exception, which you can catch, and the logical cause of the exception, which you can not catch at all. In this case, the returning and subsequent setting of the null value is a valid thing to do. It's likely in a subsequent statement that you try to send this variable (and therefore a null) some method and you're getting a null pointer exception.
In cases like this, you can only break on the subsequent null pointer exception, realize that that the cause is a null value in your variable and then to go back and debug again using breakpoints in the code to see where that null value came from.
You probably want to break the code up into multiple lines and either use a conditional breakpoint (which you can do by right clicking the line numbers if you have them displayed) or use an if statement with a normal breakpoint.
I've had trouble with conditional breakpoints and eclipse in the past so I usually go with the latter.
You could go around eclipse and write something that notifies you of the error before creating the HashMaps:
if (RsessionVars.get(sessionVars, Constants.SVAR_ENC_PRESET_LAST_KDF_MAP) == null)
System.out.println("RsessionVars.get() returned null");
Maybe your workspace is not setted correctly to handle such errors. If you go under Window -> Preferences -> Java -> Debug you should have a list of options available. The one you might want to look into is the "Suspend execution on uncaught exceptions". If checked, Eclipse will put an automatic breakpoint if the exception is not caught.
Also, if you ever know what type of exception might be, you can add a "Java Exception Breakpoint", available in the Debug/Breakpoint window (the "J" with and exclamation mark), it's an useful feature when you know what you are searching. Other than that, seperating your code in multiple lines is easier to read and to debug.
Can somebody tell me what I am doing wrong over here,
(Util.parseBoolean((String)request.getAttribute("testVal"), false))
I am getting this error.
java.lang.ClassCastException: java.lang.Boolean incompatible with java.lang.String
If what value I get from the request would do this. Thanks
Util just looks for request value and if it is y or true than sends back boolean value true. but my issue is when it goes to this line its throwing exception saying that error so I am not able to know whats happening
When you get an exception and you don't understand what's causing it, a good first step is to isolate exactly where it is happening. There are a lot of things happening in that one line of code, so it's difficult to know exactly what operation is causing the error.
Seeing the full stack trace of the exception might help, since it would give an idea of where you are in the execution path when the exception occurs.
However, a simple debugging technique is to break that one line with many operations into many lines with fewer operations, and see which line actually generates the exception. In your case this might be something like:
Object o = request.getAttribute("testVal");
String s = (String) o;
boolean b = Util.parseBoolean( s, false )
If the cause suggested by Shivan Dragon is correct, then the exception would occur on the second of these three lines.
Most likely this code: request.getAttribute("testVal") returns a Boolean, which cannot be cast to String, hence the (runtime) exception.
Either:
check for code that populates the request attribute "testVal" with the boolean value (something like request.setAttribute("testVal", Boolean.FALSE)) and replace the value with a String
or
Don't cast the value to String in your code, and don't use what seems to be a utility class for building a boolean value out of a String (*)
(*) which, btw, the Boolean class can do all by its lonesome self, no need to make your own library for that:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Boolean.html#valueOf(java.lang.String)
the value memanufacturer is retrieved from xml document using jdom and when this value is assigned to meman array it throws NullPointerException.
Element memanufacturer = (Element) row27.get(j9);
meman[0] = memanufacturer.getValue();
what could be the posssible mistake.
Thanks
Assuming the exception by the second line of code, there are two obvious possibilities:
memanufacturer may be null
meman may be null
We can't tell which of these is the case, but you should be able to.
EDIT: Okay, so now we know that meman is null, that's the problem. I would suggest you use a List<String> instead:
List<String> meman = new ArrayList<String>();
...
Element memanufacturer = (Element) row27.get(j9);
meman.add(memanufacturer.getValue());
Using a List<String> instead of an array means you don't need to know the size before you start.
However, the fact that you didn't understand the error suggests you should really read a good introductory Java book before going any further with a real project. You should definitely understand how arrays, collections etc work before dealing with XML and the like. It will save you a lot of time in the long run.