Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Preventing NullPointerException

75% developed
From Wikibooks, open books for an open world
<Java Programming

Unchecked ExceptionsJava Programming
Preventing NullPointerException
Stack trace
NavigateExceptions topic:()


NullPointerException is aRuntimeException. In Java, a specialnull can be assigned to an object reference.NullPointerException is thrown when an application attempts to use an object reference, having thenull value.These include:

  • Calling an instance method on the object referred by a null reference.
  • Accessing or modifying an instance field of the object referred by a null reference.
  • If the reference type is an array type, taking the length of a null reference.
  • If the reference type is an array type, accessing or modifying the slots of a null reference.
  • If the reference type is a subtype ofThrowable, throwing a null reference.

Applications should throw instances of this class to indicate other illegal uses of the null object.

ExampleCode section 6.13: Null pointer.
Objectobj=null;obj.toString();// This statement will throw a NullPointerException

The above code shows one of the pitfall of Java, and the most common source of bugs. No object is created and the compiler does not detect it.NullPointerException is one of the most common exceptions thrown in Java.

Why do we neednull?

[edit |edit source]

The reason we need it is because many times, we need to create an object reference before the object itself is created. Object references cannot exist without a value, so we assign thenull value to it.

ExampleCode section 6.14: Non-instantiated declared object.
publicPersongetPerson(booleanisWoman){Personperson=null;if(isWoman){person=createWoman();}else{person=createMan();}returnperson;}

In thecode section 6.14 we want to create thePerson inside the if-else, but we also want to return the object reference to the caller, so we need to create the object reference outside of the if-else, because of thescoping rule in Java. Incorrect error-handling and poor contract design can be a pitfall with any programming language. This is also true for Java.

Now we will describe how to preventNullPointerException. It does not describe general techniques for how you should program Java. It is of some use, to make you more aware of null values, and to be more careful about generating them yourself.

This list is not complete — there are no rules for preventingNullPointerException entirely in Java, because the standard libraries have to be used, and they can causeNullPointerExceptions. Also, it is possible to observe an uninitialized final field in Java, so you can't even treat a final field as being completely trusted during the object's creation.

A good approach is to learn how to deal withNullPointerExceptions first, and become competent with that. These suggestions will help you to cause lessNullPointerExceptions, but they don't replace the need to know aboutNullPointerExceptions.

Comparing string variable with a string literal

[edit |edit source]

When you compare a variable with a string literal, most of people would do that this way:

ExampleCode section 6.15: Bad comparison.
if(state.equals("OK")){...}

Always put the string literal first:

ExampleCode section 6.16: Better comparison.
if("OK".equals(state)){...}

If thestate variable is null, you get aNullPointerException in the first example, but not in the second one.

Minimize the use of the keyword 'null' in assignment statements

[edit |edit source]

This means not doing things like:

ExampleCode section 6.17: Declaring an exception.
Strings=null;while(something){if(something2){s="yep";}}if(s!=null){something3(s);}

You can replace this with:

ExampleCode section 6.18: Declaring an exception.
booleandone=false;while(!done&&something){if(something2){done=true;something3("yep");}}

You might also consider replacing null with "" in the first example, but default values bring about bugs caused by default values being left in place. ANullPointerException is actually better, as it allows the runtime to tell you about the bug, rather than just continue with a default value.

Minimize the use of the new Type[int] syntax for creating arrays of objects

[edit |edit source]

An array created usingnew Object[10] has 10 null pointers. That's 10 more than we want, so use collections instead, or explicitly fill the array at initialization with:

ExampleCode section 6.19: Declaring an exception.
Object[]objects={"blah",5,newFile("/usr/bin")};

or:

ExampleCode section 6.20: Declaring an exception.
Object[]objects;objects=newObject[]{"blah",5,newFile("/usr/bin")};

Check all references obtained from 'untrusted' methods

[edit |edit source]

Many methods that can return a reference can return a null reference. Make sure you check these. For example:

ExampleCode section 6.21: Declaring an exception.
Filefile=newFile("/etc");File[]files=file.listFiles();if(files!=null){stuff}

File.listFiles() can return null if/etc is not a directory.

You can decide to trust some methods not to return null, if you like, but that's an assumption you're making. Some methods that don't specify that they might return null, actually do, instead of throwing an exception.

For each loop trap

[edit |edit source]

Beware if you loop on an array or a collection in a for each loop.

ExampleCode section 6.22: Visit a collection.
Collection<Integer>myNumbers=buildNumbers();for(IntegermyNumber:myNumbers){System.out.println(myNumber);}

If the object is null, it does not just do zero loops, it throws a null pointer exception. So don't forget this case. Add anif statement or return empty collections:

ExampleCode section 6.23: Visit a collection safety.
Collection<Integer>myNumbers=buildNumbers();if(myNumbers!=null){for(IntegermyNumber:myNumbers){System.out.println(myNumber);}}

External tools

[edit |edit source]

There is tools like FindBugs that parse your code and warn you about potential bugs. Most of the time, it detects possible null pointers.


Clipboard

To do:
Add some exercises like the ones inVariables


Unchecked ExceptionsJava Programming
Preventing NullPointerException
Stack trace
Retrieved from "https://en.wikibooks.org/w/index.php?title=Java_Programming/Preventing_NullPointerException&oldid=4376498"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp