Why is `exception` not visible anywhere? - java

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.

Related

Handling Null Pointer Exceptions [duplicate]

This question already has answers here:
Gracefully avoiding NullPointerException in Java
(9 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So working through a few Java based web applications, I realized one common thing in pretty much most of the web applications. Most of them tend to run fine until you meet face to face with a Null Pointer Exception. Below is one of the methods that is returning an error:
public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {
Map webSiteObjects = new HashMap();
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
Scenario: This method generates a tree on my application, however, it's giving a null pointer exception at runtime:
2014-10-09 12:00:18,674 ERROR org.springframework.web.servlet.DispatcherServlet - Could not complete request
java.lang.NullPointerException at com.bsdeurope.xmlcms.service.impl.TreeManagerImpl.getWebSiteObjects(TreeManagerImpl.java:159)
Now I'm quite new with some Java principals(fundamentals) and my idea to solve this was to initialize the 4 variables passed in the method therefore have:
path = null;
root =null;
versionId = null;
site = null;
before any instructions within the getWebSiteObjects method. Now I know this might not be the only solution but my question is:
1) What is good practice in terms of preventing Java Null Pointer Exceptions?
2) If there is a procedure how would you go about doing it?
Usually when working with a lot of classes especially applications with code that is badly written you end up hitting your head against the wall when you get tons of null pointer exceptions left, right and center.
There are two schools of thought on this.
One school, says test for the null and do something to "make good". For example, replace it with something else, ignore it, write a log message, and so on.
The other school is that an unexpected null is a BUG, and the correct thing to do is to allow the NullPointerException to be thrown. Then you allow the NPE to propagate up and (ideally) cause the program to crash ... or better still, fail gracefully after logging the NPE stacktrace in the application's log files.
Then it is up to the programmer to use the information in the stacktrace (and "those little grey cells" to quote a well-known fictional Belgian detective) to figure out where the unexpected null came from, and fix the root cause of the problem. Typically this entails finding the field or array element or whatever that was incorrectly initialized, of the get call that returns a null to indicate (soft) failure, or whatever. This fix may involve testing for null, or it may involve initializing something, or passing something, or correcting some logic, or adding the null test earlier in the program.
IMO, the practice of adding defensive tests for null all over the place is a bad idea. It tends to replace one kind of bug (an NPE) with another kind that is often harder to track down.
So my answers would be:
1) What is good practice in terms of preventing Java Null Pointer Exceptions?
Good practice is to not avoid the NPEs. Instead let them happen, and find / fix what is introducing the spurious null values.
2) If there is a procedure how would you go about doing it?
No there isn't. Certainly there is no procedure that >>I<< would use.
The only thing I would do would be to try to make my code throw the NPE earlier, so that the null doesn't get passed a long way from its original source. (That tends to make it easier to find and fix the root cause of the problem.)
A null check is usually enough.
// refresh site
if(site!=null){
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}else{
// Print an error message, or do the error handling here...
}
Note that, NullPointerException will only come when your expression evaluates to null.someFunction() . In this example, site.getId(). So null check for only site!=null is enough. If you have more object.someFunction() then you may want to do something like
if(obj1!=null && obj2!=null){
// Safe to call
obj1.function();
obj2.function();
}
For you Program here is a simple null check:
public Map getWebSiteObjects(String path, LightWeightNode root, Integer versionId, Site site) {
Map webSiteObjects = new HashMap();
if(null!=Site){
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}
//Similarly while using other arguments do similar null check
(if null!=path){
/*
Your code here...
*/
}
}
For best practices to avoid NPE check this link: NPE practices
you can put all your business logic of any method in try block
try{
Map webSiteObjects = new HashMap();
// refresh site
site = (Site)getObject(Site.class, site.getId());
webSiteObjects.put("site", site); ...... /* Dont worry about the rest */
}catch(NullPointerException e){
// error occured
e.printStackTrace();
}

netbeans debugging best practice

[Edit: Let me rephrase]
Say an object o that occurs in debugging has properties a and b, with values null and Hello. Is it possible to automatically generate the following code for the next debugging session:
if(o.a == null && o.b == "Hello") {
}
When debugging a program that has to cope with complex user inputs, such as a parser for a programming language, I often want to start debugging from a certain point in the process of parsing. I have implemented a simple way of starting when an instruction from a specific line of input code is handled.
However, lines may contain very complex instructions resulting in deep recursions in the code, such that after starting the debugging I have to step farther into the program manually. When this happens in a function func(obj a), I usually write some ugly code like this:
public void func(obj a) {
if(a instanceof someClass && ((someClass)a).hasSomeProperty() && ((someClass)a).getIdentifier().equals("myID")) {
// set a breakpoint here
}
// other code
}
So basically I try to identify the interesting situation by identifying an object that was passed to a function. I know these values because I usually have a breakpoint on an exception that is thrown in the other code. So my question is this: instead of writing all this ugly code to generate a proper breakpoint, is there a way to configure a conditional breakpoint based on some value that a variable has in a former debugging session? Basically say: halt here when the object is exactly like this one here?
You might do the following: write a static utility method ("writer") that serializes and writes the object you want to compare with a future debugging session; and another method ("reader") which receives an Object and compares it with the serialized version, returning true when both are equal.
After that, you can define one or more conditional breakpoints which call up the "writer" method and don't stop.
Additionally, you'd define another conditional breakpoint calling the "reader" method, which halts the thread as usual but only when the condition is met.
Netbeans offers the conditional breakpoint feature: after you set a breakpoint on a line you right click on it, choose Breakpoint-Properties, select the Condition checkbox and insert Java code to express a condition that must be true to break program execution.
add the breakpoint, right click it, go to breakpoint -> properties
at the breakpoint properties window you will see a condition box, and you add your if

String Boolean error java

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)

Java short circuit evaluation

I thought Java had short circuit evaluation, yet this line is still throwing a null pointer exception:
if( (perfectAgent != null) && (perfectAgent.getAddress().equals(entry.getKey())) ) {
In this case perfectAgent is null, so I just want the whole expression to return false, but my app is still crashing on this line with a NullPointerException.
EDIT, general response:
Since perfectAgent is null, nothing to the right of the && should be executed, as it is impossible for the expression to be true. More to the point, it is impossible to execute perfectAgent.getAddress() since perfectAgent does not contain a valid reference (it being null and all). I'm trying to use short circuit evaluation to not have to check for null in a seperate statement as that makes the logic more sloppy.
EDIT 2 (or, I'm an idiot):
Yeah, like many things in life you figure out the answer right after announcing to the world that you're a moron. In this case, I had turned off Eclipse's autobuild while doing something else and not turned it back on, so I was debugging class files that didn't match up with my source.
If perfectAgent is genuinely null, that code won't throw an exception (at least assuming there aren't weird threading things going on, changing it from non-null to null half way through the expression). I would be utterly shocked if you could produce a short but complete program demonstrating it doing so.
So yes, your intuition is right - this shouldn't be a problem. Look elsewhere for the cause. I strongly suspect that perfectAgent isn't actually null, and that you're running into any of the other situations in that code which could cause an exception.
I suggest you try to extract that bit of code out into a short but complete example - if you can do so, I'll eat my metaphorical hat; if not, you'll hopefully find the problem while you attempt the extraction.
What makes you think that perfectAgent really is null? Try inserting this code before it:
if (perfectAgent == null)
{
System.out.println("Yup, it's null");
}
Another very, very slim possibility is that you've run into a JIT bug - but I highly doubt it.
Java does have short circuit evaluation. Perhaps entry is null and so entry.getKey() is causing the NullPointerException. Another possibility is that getAddress() either returns null or has a NullPointerException happening inside somewhere (if it's more complicated than a simple return statement).
EDIT: I see your edit where you claim this:
More to the point, it is impossible to execute perfectAgent.getAddress() ...
But what if perfectAgent.getAddress() is successfully executed and returns null? See what I mean...
Advanced debugging lesson #1:
If you run into a seemingly impossible error (e.g. one that contradicts you knowledge about Java), do the following:
Consult a reputable text book (or better still, the relevant standard) to confirm that your understanding is not flawed. (In this case your understanding was correct, and any half-decent textbook would confirm this in a minute.)
Check all of the stupid things that you could have done that could cause the impossible error. Things like not saving a file, not doing a complete build, running an old / stale version of the application, being in the wrong directory, and so on.
In summary, learn to doubt yourself a bit more.
You ensure that perfectAgent is not null, so one or more of perfectAgent.getAddress() or entry or entry.getKey() must be null. Or getAddress() or getKey() are hitting an NPE in their implementation.
To debug this sort of thing, look first at the stack trace to pin down the location. This would tell you if it's happening in getAddress() or in getKey() or in the pasted code snippet that calls them. Next, if it's in this snippet, add some code before the if to test which is null. You can use good old System.err.println() or assertions. (If you use assertions, be sure to enable them with the java command's -enableassertions flag.)
Update: So my interpretation turned out to be wrong ... the problem presented two contradictory facts (there was an NPE on this line and yet the short-circuit should have happened) and I automatically assumed the first fact was true and the second false when in fact it was a different problem entirely due to turning off the auto-build in Eclipse. Duh! In debugging something "impossible" it helps to be radically skeptical.
There are three references other than perfectAgent that could be null:
perfectAgent.getAddress()
entry
entry.getKey()
Break up the statement or run it in a debugger.
Big mistery. I copied your line of code and tested with perfectAgent == null, entry == null, entry.getKey() == null and combinations of those: No NPE in my test bed (Java 1.6).
Whatever annoying bug it is, I doubt that it has something to do with short circuit evaluation. If it's this line causing NPE, than, as far as I can say, perfectAgent is not null. Good luck and - show us the bug once you've catched it :)
Try formatting your code like this:
if(
(perfectAgent != null)
&& (
perfectAgent.getAddress()
.equals(
entry.getKey()
)
)
) {
It should give you a better stack trace line entry.

How to trace a NullPointerException in a chain of getters

If I get a NullPointerException in a call like this:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
I get a rather useless exception text like:
Exception in thread "main" java.lang.NullPointerException
at package.SomeClass.someMethod(SomeClass.java:12)
I find it rather hard to find out which call actually returned null, often finding myself refactoring the code to something like this:
Foo ret1 = someObject.getSomething();
Bar ret2 = ret1.getSomethingElse();
Baz ret3 = ret2.getAnotherThing();
Bam ret4 = ret3.getYetAnotherOject();
int ret5 = ret4.getValue();
and then waiting for a more descriptive NullPointerException that tells me which line to look for.
Some of you might argue that concatenating getters is bad style and should be avoided anyway, but my Question is: Can I find the bug without changing the code?
Hint: I'm using eclipse and I know what a debugger is, but I can't figuer out how to apply it to the problem.
My conclusion on the answers:
Some answers told me that I should not chain getters one after another, some answers showed my how to debug my code if I disobeyed that advice.
I've accepted an answer that taught me exactly when to chain getters:
If they cannot return null, chain them as long as you like. No need for checking != null, no need to worry about NullPointerExceptions (be warned that chaining still violates the Law of Demeter, but I can live with that)
If they may return null, don't ever, never ever chain them, and perform a check for null values on each one that may return null
This makes any good advice on actual debugging useless.
NPE is the most useless Exception in Java, period. It seems to be always lazily implemented and never tells exactly what caused it, even as simple as "class x.y.Z is null" would help a lot in debugging such cases.
Anyway, the only good way I've found to find the NPE thrower in these cases is the following kind of refactoring:
someObject.getSomething()
.getSomethingElse()
.getAnotherThing()
.getYetAnotherObject()
.getValue();
There you have it, now NPE points to correct line and thus correct method which threw the actual NPE. Not as elegant solution as I'd want it to be, but it works.
The answer depends on how you view (the contract of) your getters. If they may return null you should really check the return value each time. If the getter should not return null, the getter should contain a check and throw an exception (IllegalStateException?) instead of returning null, that you promised never to return. The stacktrace will point you to the exact getter. You could even put the unexpected state your getter found in the exception message.
In IntelliJ IDEA you can set exceptionbreakpoints. Those breakpoints fire whenever a specified exception is thrown (you can scope this to a package or a class).
That way it should be easy to find the source of your NPE.
I would assume, that you can do something similar in netbeans or eclipse.
EDIT: Here is an explanation on how to add an exceptionbreakpoint in eclipse
If you find yourself often writing:
a.getB().getC().getD().getE();
this is probably a code smell and should be avoided. You can refactor, for example, into a.getE() which calls b.getE() which calls c.getE() which calls d.getE(). (This example may not make sense for your particular use case, but it's one pattern for fixing this code smell.)
See also the Law of Demeter, which says:
Your method can call other methods in its class directly
Your method can call methods on its own fields directly (but not on the fields' fields)
When your method takes parameters, your method can call methods on those parameters directly.
When your method creates local objects, that method can call methods on the local objects.
Therefore, one should not have a chain of messages, e.g. a.getB().getC().doSomething(). Following this "law" has many more benefits apart from making NullPointerExceptions easier to debug.
I generally do not chain getters like this where there is more than one nullable getter.
If you're running inside your ide you can just set a breakpoint and use the "evaluate expression" functionality of your ide on each element successively.
But you're going to be scratching your head the moment you get this error message from your production server logs. So best keep max one nullable item per line.
Meanwhile we can dream of groovy's safe navigation operator
Early failure is also an option.
Anywhere in your code that a null value can be returned, consider introducing a check for a null return value.
public Foo getSomething()
{
Foo result;
...
if (result == null) {
throw new IllegalStateException("Something is missing");
}
return result;
}
Here's how to find the bug, using Eclipse.
First, set a breakpoint on the line:
someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
Run the program in debug mode, allow the debugger to switch over to its perspective when the line is hit.
Now, highlight "someObject" and press CTRL+SHIFT+I (or right click and say "inspect").
Is it null? You've found your NPE. Is it non-null?
Then highlight someObject.getSomething() (including the parenthesis) and inspect it.
Is it null? Etc. Continue down the chain to figure out where your NPE is occurring, without having to change your code.
You may want to refer to this question about avoiding != null.
Basically, if null is a valid response, you have to check for it. If not, assert it (if you can). But whatever you do, try and minimize the cases where null is a valid response for this amongst other reasons.
If you're having to get to the point where you're splitting up the line or doing elaborate debugging to spot the problem, then that's generally God's way of telling you that your code isn't checking for the null early enough.
If you have a method or constructor that takes an object parameter and the object/method in question cannot sensibly deal with that parameter being null, then just check and throw a NullPointerException there and then.
I've seen people invent "coding style" rules to try and get round this problem such as "you're not allowed more than one dot on a line". But this just encourages programming that spots the bug in the wrong place.
Chained expressions like that are a pain to debug for NullPointerExceptions (and most other problems that can occur) so I would advise you to try and avoid it. You have probably heard that enough though and like a previous poster mentioned you can add break points on the actual NullPointerException to see where it occurred.
In eclipse (and most IDEs) you can also use watch expressions to evaluate code running in the debugger. You do this bu selecting the code and use the contet menu to add a new watch.
If you are in control of the method that returns null you could also consider the Null Object pattern if null is a valid value to return.
Place each getter on its own line and debug. Step over (F6) each method to find which call returns null

Categories

Resources