java dereferencing possible null pointer - java

In my code I get the above warning. Here is the part of the code where I get it,
try {
fileFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
} catch (URISyntaxException | NullPointerException e) {
}
finally {
if (fileFile.getPath()!= null){
strPathName = fileFile.getPath();
}
if (fileFile.getName() != null){
strFileName = fileFile.getName();
}
}
The line if (fileFile.getPath()!= null){ is the one with the warning.
This code is not part of the Main class. It's in another class in another class file in the same package.
I'm not very experienced with programming but I believe I did nearly everything to prevent or catch a null pointer exception. Why do I still getting it and what can I do to get rid of it? Thanks for your help.
After reading all your hints I solved it. Here is the complete code:
public static ArrayList<String> getCurrentPath() {
File fileFile;
String strPathName, strFileName;
ArrayList<String> arrPathFileName;
strFileName = null;
strPathName = null;
try {
fileFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
if (fileFile.getPath()!= null){
strPathName = fileFile.getPath();
}
if (fileFile.getName() != null){
strFileName = fileFile.getName();
}
} catch (URISyntaxException use) {
}
arrPathFileName = new ArrayList<>();
arrPathFileName.add(strPathName);
arrPathFileName.add(strFileName);
return arrPathFileName;
}
As already mentioned I simply put the if statements into the try block and removed the finally block.
BTW is also tried to combine both if blocks into one that way:
if (fileFile != null){
strPathName = fileFile.getPath();
strFileName = fileFile.getName();
}
But that produced a warning that fileFile will never become null. (what was my point of view from the beginning and so the warning "dereferencing possible null pointer" was really confusing me.)

So if you throw an exception on your first line, your variable will not be assigned to a File, and will retain it's previous value (null if not formerly assigned). Your exception is caught, and then you continue to use that unassigned variable. Hence the warning. See the commented code below.
try {
fileFile = // exception thrown. Variable not assigned
} catch (URISyntaxException | NullPointerException e) {
// exception caught
}
finally {
// unassigned variable used here...
if (fileFile.getPath()!= null){
strPathName = fileFile.getPath();
}
if (fileFile.getName() != null){
strFileName = fileFile.getName();
}
}
I would rather scope and use the variable within the try block, if at all practical. In your finally block, you need to be as careful as you can, since you could have come to it from most anywhere in your try block.
As an aside, this:
Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
will cause you enormous problems if you do get an NPE. Which of the above resolved to null ? I would perhaps be more explicit, such that you can check for nulls from each invocation and unambiguously determine which invocation gave you a null. Tiresome ? Unfortunately so.

A "null pointer dereference" is computer speak for trying to call a method on a null value. It's a little more complicated, but you said you were a novice, so I wanted to keep it simple.
Let's see an example:
String s = null;
s = s.toUpperCase();
This is a simple example of what a null pointer dereference is. s is a null reference (its value is null), when we derefrence is (get the value of it) we have null, when we call toUpperCase() on null, something goes horribly wrong because null doesn't have any methods, at all! Java throws a NullPointerException to be specific.
Now, back to your code, because fileFile is assigned in the try-block I assume it was set to null before it to avoid Java yelling about an uninitialized variable. (This is all fine and correct.) In this try-block, if any of the exceptions for your catch-block occur it will stop the try-block (meaning fileFile will not get a new value, meaning it will still be null).
Now you'll notice the warning is possible null pointer dereference. That means it won't necessarily be null, but could be! (In my above example, it's always a null pointer dereference for comparison.) Specifically, if the catch catches an exception it will be null.
To be clear, the issue is this: fileFile.getPath(). It's like saying it might be null.getPath(), gross. It looks like you were trying to avoid the null pointer issue, what you should have done was if (fileFile != null) { instead. Then inside of the if do what you want.
Also, because it seems like you included it to avoid this warning, I would seriously remove the NullPointerException from the catch-block. That's not helping you avoid the warning. If you want me to explain more why it's bad you can leave a comment and I will, otherwise just take my word for it, it's not helping you.

Related

Loop Null Pointer Exception

If the newWord is null ,it should not go in the loop,but why does it go inside the loop and gives java.lang.NullPointerException
newWord = "abcd";
while(!newWord.equals(null))
{
try {
newWord = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NullPointerException p)
{
}
}
It gives the stacktrace but i have not used printStackTrace() anywhere
newWord itself is null. When an object is null, you can't call any methods on it as the object is not defined. As .equals is a method, you are getting an exception. Try this instead:
newWord != null
This is a problem easily solved by debugger. Learning to use a debugger is frustrating (as is learning any new tool,) but it will save you many hours of pain. It is your friend.
how about simply
while(newWord!=null)
Think about it, If newWorld is null, what happens when you call methods on it ?
It doesn't go into the loop because
newWOrd.equals(null)
will throw an NPE if it is null
What you meant was
newWord != null
You can see this behaviour if you use a debugger, or look at the line in your stack trace where it is triggered.
You only check if "newWord" is null, never if "br" has anything left reading from.
Something like:
while(br.hasNext());
the NullPointerException you are getting is because of while(!newWord.equals(null)) and it is not caught because try , catch were used after this code.
If you want to suppress this exception to then put that while(!newWord.equals(null)) in try-catch block.
!newWord.equals(null)
is your problem.
Use newWord != null
The argument for String.equal should not be null and explicitly null is passed so is the exception. Use compound expression to check for empty string and special null.
It tried to evaluate the expression before entering loop, soon the expression is encountered !newWord.equals(null), because of newWord being null an exception were thrown.
to avoid null exception in most of the cases (inside conditional expressions) I advise you to use Yoda conditions:
if(null != value)
Furthemore, this apply to every condition between a variable and a constant:
if(MY_CONSTANT_STRING.equals(myVariableString))

A try-catch scenario - correct to use checked or not

I am looking at a code base where the domain model consists of many nested member variables.
Consider this scenario
private static String getSomeStringRepresentation(A input) {
String result = "";
try {
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}
In this call chain, any method call can result in a NullPointerException. Is it correct to handle it with a catch clause in this case? Is this a case where "it is possible to handle the exception" ?
Edit
The case of checking for null four times is really ugly. Don't you consider catching the NPE is justified in this case?
The problem here is calling some method on a object that possibly could be null.
Why don't you check for null rather than putting a catch block? Catching NullPointerException isn't considered good practice.
If catching null pointer exception is not a good practice, is catching exception a good one?
also
Is Catching a Null Pointer Exception a Code Smell?
Catching a NullPointerException is not a good practice without a serious reason:
Rather check for null object like this:
private static String getSomeStringRepresentation(A input) {
String result = "";
try {
if(input != null && input.getTypeA() != null && input.getTypeA().getTypeAInfo() != null && getTypeAInfo().get(0) != null){
result = input.getTypeA().getTypeAInfo().get(0).getRepresentation();
}
} catch (NullPointerException e) {
Logger.logDebug(e.getMessage());
}
return result;
}
Here is a possible duplicate on the subject.
NPEs are just an error in the code and should therefore not be catched - they should be fixed.
NullPointerException indicates a programming error, catching it is wrong. Instead of catching it fix bugs in your program.

java. Method return Null. What exception I must generated?

I have this line code:
String name = Book.getName();
/*next lines of code*/
Next, variable name processing in other code without any checks.
In some cases, possible situation, when name=null and other code will exit with an error.
It is bad.
Also, I cant access to the other code.
So, what do you think, my next implementation is correct:
try
{
String name = Book.getName();
if(null== name)
throw new NullPointerException("method 'getName' return null");
/*next lines of code*/
}
catch(NullPointerException e)
{
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
I have any other choose in this case?
It is possible to generate any other type of Exception or only NullPointerException?
Thanks.
Edit:
Ok,
String name = Book.getName();
it's imagine code line. In real case, I have more complex code:
List<Book> bookList= new ArrayList<Book>();
String name = null;
Iterator i = BookShop.getBooks.iterator(); //BookShop it is input parameter!
while(i.hasNext())
{
Book book = (Book) i.next;
name = book.getName();
nameList.add(name);
}
This example more full.
So, in this code input parameter BookShop Object.
What problem I can have with this Object?
BookShop can be NULL;
method BookShop.getBooks() can return NULL;
Also, getName() can return NULL too.
So, general problem next: there is no guarantee the correctness of input parameter BookShop!
And I must to consider every possible option (3 NULL)
For me, add General try-catch block and that all.
No?
You can create any exception you like by extending the Exception class, like a NoNameProvidedException for example. There are a lot of example one Google to help you do that.
I guess in your case just checking with an if if the name is null should be sufficient as you just want to do a System.exit().
Your code is a bit iffy, but I assume you're learning. You don't need to throw the NullPointerException explicitly, you can throw whatever Exceptions you like.
But you probably don't really need the Exception catching here, you can just check for the null and handle the situation appropriately if it's true.
Also, please avoid Yoda conditions. Your if statement should read
if name is null
so
if (name == null)
I would probably use IllegalStateException:
String name = Book.getName();
if (name == null) {
throw new IllegalStateException
("Method foo must not be called when the book has no name");
}
It really depends on where the state is coming from though - it's not really clear what's going wrong here.
I certainly wouldn't start catching NullPointerException - exceptions like that (and the illegal state one) shouldn't be explicitly caught. Let them bubble up, and if it's appropriate have some sort of top-level handler.
Exceptions should not be used for normal control flow. Just use the if block:
String name = Book.getName();
if (name == null) {
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
/*next lines of code*/
Using try and catch in this case is unneeded. You can just write like this:
if(Book.getName() != null)
String name = Book.getName();
else
//handle the situation with null
You don't need to throw an Exception in this case - just handle the null value and you are fine.
It's more friendly for Java not to use exceptions, but just check the return value
String name = Book.getName();
if (name == null)
System.out.print("Hey! Where book name? I exit!");
else {
/*next lines of code*/
}

NullPointerException, logical shortcut

Here is a simple code snippet and I cannot figure out why does it throw a NullPointerException.
String lastGroup = "";
menuTevekenysegekGrouped = new ArrayList<MenuElem>();
for(MenuElem me : menuA) {
// double checked that me objects are never null
// double checked that menuA is never null
if(me.getGroup() != null && !me.getGroup().equals(lastGroup)) { /* NPE!!! */
lastGroup = me.getGroup();
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
In the first iteration the me.getGroup() returns null. So the first operand of the && is false and second operand should not evaluate according to the JLS, as far as I know. However when I debug the code I get NPE from the marked line. I'd like to know why. (Using JRockit 1.6.0_05 if it matters..)
Are you sure that me itself is not, in fact, null?
From your code (without the stacktrace I have to guess), the following may be null and be the cause: menuA or me or menuTevekenysegekGrouped. And some of the values returned from the methods/or used in the methods may also be null, but it's hard to know...
If me is not null, then the only other object that can be null in the above snippet is menuTevekenysegekGrouped. Add a check before first using it to ensure that it's not null.
The repeated calls to me.getGroup() would bug me enough to pull them out into a local variable:
String lastGroup = "";
for(MenuElem me : menuA) {
String thisGroup = me.getGroup();
if(thisGroup != null && !thisGroup.equals(lastGroup)) {
lastGroup = thisGroup;
MenuElem separ = new MenuElem();
separ.setCaption(lastGroup);
separ.setGroupHead(true);
menuTevekenysegekGrouped.add(separ);
menuTevekenysegekGrouped.add(me);
} else {
menuTevekenysegekGrouped.add(me);
}
}
This is only going to fix your problem if in fact me.getGroup() returns different values (sometimes null) on multiple calls with the same me, but it might make it easier to debug, and certainly makes it easier to read.

Java Null Reference Best Practice

In java, Which of the following is the more "accepted" way of dealing with possibly null references? note that a null reference does not always indicate an error...
if (reference == null) {
//create new reference or whatever
}
else {
//do stuff here
}
or
try {
//do stuff here
}
catch (NullPointerException e) {
//create new reference or whatever
}
The answers already given are excellent (don't use exceptions for control flow; exceptions are expensive to throw and handle). There's one other important reason specifically not to catch NullPointerException.
Consider a code block that does the following:
try {
reference.someMethod();
// Some other code
}
catch (NullPointerException e) {
// 'reference' was null, right? Not so fast...
}
This might seem like a safe way to handle nullity of reference ...but what if reference was non-null and someMethod() raised NPE? Or what if there was a NPE raised elsewhere in the try block? Catching NPE is a surefire way to prevent bugs from being found and fixed.
Catching exceptions is relatively expensive. It's usually better to detect the condition rather than react to it.
Of course this one
if (reference == null) {
//create new reference or whatever
}
else {
//do stuff here
}
we shouldn't rely on exception for decision making, that aren't given for that purpose at all, also they are expensive.
Well If you aren't making decision and just verifying for initialized variable then
if (reference == null) {
//create new reference or whatever
}
//use this variable now safely
I have seen some auto code generator wraps up this thing in accessors/getter method.
I think in general an exception should be reserved for exceptional circumstances - if a null reference is sometimes expected, you should check for it and handle it explicitly.
From the answers its clear that catching an exception is not good. :)
Exceptions are definitely not free of cost. This might help you to understand it in depth. .
I would also like to mention an another practice while comparing your object with a known value.
This is the traditional way to do the job: (check whether the object is null or not and then compare)
Object obj = ??? //We dont know whether its null or not.
if(obj!=null && obj.equals(Constants.SOME_CONSTANT)){
//your logic
}
but in this way, you dont have to bother about your object:
Object obj = ???
if(Constants.SOME_CONSTANT.equals(obj)){ //this will never throw
//nullpointer as constant can not be null.
}
The first one, throwing exceptions is a costly operation.
The first form:
if (reference == null)
{
//create new reference or whatever
}
else
{
//do stuff here
}
You should not use exceptions for control flow.
Exceptions are for handling exceptional circumstances that would not normally occur during normal operating conditions.
You should use exception catching where you do not expect there to be an error. If something can be null, then you should check for that.
maybe the try catch approach will start making sense in this situation when we can start doing
try {
//do stuff here
}
catch (NullPointerException e) {
//create new reference or whatever
retry;
}
This is related to your style of development, if you are developing code using "safe" style you have to use
if(null == myInstance){
// some code
}else{
// some code
}
but if you do not use this style at least you should catch exception, but in this case it NullPointerException and I think preferably to check input parameters to null and not wait to throwing exception.
Since you asked for Best Practices, I want to point out that Martin Fowler suggests to introduce a subclass for null references as best practice.
public class NullCustomer extends Customer {}
Thus, you avoiding the hassle of dealing with NullPointerException's, which are unchecked. Methods which might return a Customer value of null, would then instead return a NullCustomer instead of null.
Your check would look like:
final Customer c = findCustomerById( id );
if ( c instanceof NullCustomer ) {
// customer not found, do something ...
} else {
// normal customer treatment
printCustomer( c );
}
In my opinion, it is permissible in some cases to catch a NullPointerException to avoid complex checks for null references and enhance code readability, e.g.
private void printCustomer( final Customer c ) {
try {
System.out.println( "Customer " + c.getSurname() + " " + c.getName() + "living in " + c.getAddress().getCity() + ", " + c.getAddress().getStreet() );
} catch ( NullPointerException ex ) {
System.err.println( "Unable to print out customer information.", ex );
}
An argument against it is that by checking for individual members being null, you can write a more detailed error message, but that is often not necessary.

Categories

Resources