Domanda

Quali sono le eccezioni del puntatore null ( java.lang.NullPointerException ) e quali sono le cause?

Quali metodi / strumenti possono essere utilizzati per determinare la causa in modo da impedire all'eccezione di terminare prematuramente il programma?

È stato utile?

Soluzione

Quando dichiari una variabile di riferimento (cioè un oggetto) stai davvero creando un puntatore a un oggetto. Considera il codice seguente in cui dichiari una variabile di tipo primitivo int :

int x;
x = 10;

In questo esempio, la variabile x è un int e Java lo inizializzerà su 0 per te. Quando gli assegni il valore di 10 sulla seconda riga, il tuo valore di 10 viene scritto nella posizione di memoria a cui fa riferimento x .

Ma quando provi a dichiarare un tipo di riferimento, succede qualcosa di diverso. Prendi il seguente codice:

Integer num;
num = new Integer(10);

La prima riga dichiara una variabile denominata num , ma in realtà non contiene ancora un valore primitivo. Al contrario, contiene un puntatore (poiché il tipo è Integer che è un tipo di riferimento). Dato che non hai ancora detto cosa indicare, Java lo imposta su null , il che significa " Sto indicando nulla " ;.

Nella seconda riga, la parola chiave new viene utilizzata per creare un'istanza (o creare) un oggetto di tipo Integer e la variabile puntatore num è assegnato a quell'oggetto Integer .

Il NullPointerException si verifica quando si dichiara una variabile ma non si crea un oggetto. Quindi stai indicando qualcosa che in realtà non esiste.

Se si tenta di dereferenziare num PRIMA di creare l'oggetto, si ottiene un NullPointerException . Nei casi più banali, il compilatore rileverà il problema e ti informerà che " num potrebbe non essere stato inizializzato , " ma a volte puoi scrivere codice che non crea direttamente l'oggetto.

Ad esempio, potresti avere un metodo come segue:

public void doSomething(SomeObject obj) {
   //do something to obj
}

In tal caso, non si sta creando l'oggetto obj , ma si assume piuttosto che sia stato creato prima che fosse chiamato il metodo doSomething () . Nota, è possibile chiamare il metodo in questo modo:

doSomething(null);

In tal caso, obj è null . Se il metodo ha lo scopo di fare qualcosa sull'oggetto passato, è opportuno lanciare NullPointerException perché è un errore del programmatore e il programmatore avrà bisogno di tali informazioni per scopi di debug.

In alternativa, ci possono essere casi in cui lo scopo del metodo non è solo quello di operare sull'oggetto passato, e quindi un parametro null può essere accettabile. In questo caso, dovresti cercare un parametro null e comportarti diversamente. Dovresti anche spiegarlo nella documentazione. Ad esempio, doSomething () potrebbe essere scritto come:

/**
  * @param obj An optional foo for ____. May be null, in which case 
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj != null) {
       //do something
    } else {
       //do something else
    }
}

Infine, Come individuare l'eccezione & amp; causa l'utilizzo di Stack Trace

Altri suggerimenti

NullPointerException s sono eccezioni che si verificano quando si tenta di utilizzare un riferimento che punta a nessuna posizione in memoria (null) come se si riferisse a un oggetto. Chiamare un metodo su un riferimento null o provare ad accedere a un campo di un riferimento null attiverà un NullPointerException . Questi sono i più comuni, ma altri modi sono elencati nella NullPointerException pagina javadoc.

Probabilmente il codice di esempio più veloce che potrei trovare per illustrare un NullPointerException sarebbe:

public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

Sulla prima riga all'interno di main , sto esplicitamente impostando il Object riferimento obj uguale a null . Questo significa che ho un riferimento, ma non punta a nessun oggetto. Successivamente, provo a trattare il riferimento come se puntasse a un oggetto chiamando un metodo su di esso. Ciò si traduce in un NullPointerException perché non esiste alcun codice da eseguire nella posizione indicata dal riferimento.

(Questo è un tecnicismo, ma penso che vada menzionato: un riferimento che punta a null non è lo stesso di un puntatore C che punta a una posizione di memoria non valida. Un puntatore null non sta letteralmente puntando da nessuna parte , che è leggermente diverso dal puntare a una posizione che risulta essere non valida.)

Che cos'è NullPointerException?

Un buon punto di partenza è il JavaDocs . Hanno questo coperto:

  

Generato quando un'applicazione tenta di utilizzare null in un caso in cui un   l'oggetto è richiesto. Questi includono:

     
      
  • Chiamare il metodo di istanza di un oggetto null.
  •   
  • Accesso o modifica del campo di un oggetto null.
  •   
  • Prendendo la lunghezza di null come se fosse un array.
  •   
  • Accesso o modifica agli slot di null come se fosse un array.
  •   
  • Lancio null come se fosse un valore gettabile.
  •   
     

Le applicazioni dovrebbero lanciare istanze di questa classe per indicarne altre   usi illegali dell'oggetto null.

È anche possibile che se si tenta di utilizzare un riferimento null con sincronizzato , ciò genererà anche questa eccezione, per JLS :

SynchronizedStatement:
    synchronized ( Expression ) Block
     
      
  • Altrimenti, se il valore dell'Espressione è null, viene generato un NullPointerException .
  •   

Come posso ripararlo?

Quindi hai un NullPointerException . Come lo risolvi? Facciamo un semplice esempio che genera un NullPointerException :

public class Printer {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void print() {
        printString(name);
    }

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");
    }

    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print();
    }
}

Identifica i valori null

Il primo passo è identificare esattamente quali valori stanno causando l'eccezione . Per questo, dobbiamo fare un po 'di debug. È importante imparare a leggere un stacktrace . Questo ti mostrerà dove è stata generata l'eccezione:

Exception in thread "main" java.lang.NullPointerException
    at Printer.printString(Printer.java:13)
    at Printer.print(Printer.java:9)
    at Printer.main(Printer.java:19)

Qui, vediamo che l'eccezione viene lanciata sulla linea 13 (nel metodo printString ). Guarda la linea e controlla quali valori sono nulli per aggiungendo istruzioni di registrazione o usando un debugger . Scopriamo che s è null e chiamando il metodo length genera l'eccezione. Possiamo vedere che il programma smette di generare l'eccezione quando s.length () viene rimosso dal metodo.

Traccia da dove provengono questi valori

Quindi controlla da dove proviene questo valore. Seguendo i chiamanti del metodo, vediamo che s viene passato con printString (nome) nel metodo print () e < code> this.name è null.

Traccia dove impostare questi valori

Dove è impostato this.name ? Nel metodo setName (String) . Con un po 'più di debug, possiamo vedere che questo metodo non è chiamato affatto. Se il metodo è stato chiamato, assicurati di controllare ordine che questi metodi siano chiamati e che il metodo set non sia chiamato dopo il metodo di stampa.

Questo è sufficiente per darci una soluzione: aggiungi una chiamata a printer.setName () prima di chiamare printer.print () .

Altre correzioni

La variabile può avere un valore predefinito (e setName può impedire che sia impostato su null):

private String name = "";

Il metodo print o printString può controllare null , ad esempio:

printString((name == null) ? "" : name);

Oppure puoi progettare la classe in modo che name abbia sempre un valore non nullo :

public class Printer {
    private final String name;

    public Printer(String name) {
        this.name = Objects.requireNonNull(name);
    }

    public void print() {
        printString(name);
    }

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");
    }

    public static void main(String[] args) {
        Printer printer = new Printer("123");
        printer.print();
    }
}

Vedi anche:

Non riesco ancora a trovare il problema

Se hai provato a eseguire il debug del problema e non hai ancora una soluzione, puoi inviare una domanda per ulteriore aiuto, ma assicurati di includere ciò che hai provato finora. Come minimo, includi lo stacktrace nella domanda e contrassegna i numeri di riga importanti nel codice. Inoltre, prova prima a semplificare il codice (vedi SSCCE ).

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labelled "HERE" is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception ... but the standard javac compiler doesn't.)

Second observation: when I run the program, it outputs two lines of "gobbledy-gook". WRONG!! That's not gobbledy-gook. It is a stacktrace ... and it provides vital information that will help you track down the error in your code, if you take the time to read it carefully.

So let's look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be "main". Let's move on ...
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • "at Test.main" says that we were in the main method of the Test class.
  • "Test.java:4" gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the "HERE" comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first "at" line) will tell you where the NPE was thrown1.

In short the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

1 - Not quite true. There are things called nested exceptions...

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code and the relevant API documentation.

Let's illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and .... BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.lang.String class, and line 4 of Test.java would be the second "at" line.

So where did that null come from? In this case it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let's try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two "at" lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null ... but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is that possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo ... so foo[1] will still be null.

It's like you are trying to access an object which is null. Consider below example:

TypeA objA;

At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.

See this below example as well:

String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown

A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.

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

Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html

A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.

In general, it's because something hasn't been initialized properly.

A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerException at all.

See also: A good list of best practices

I would add, very important, make a good use of the final modifier. Using the "final" modifier whenever applicable in Java

Summary:

  1. Use the final modifier to enforce good initialization.
  2. Avoid returning null in methods, for example returning empty collections when applicable.
  3. Use annotations @NotNull and @Nullable
  4. Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
  5. Use equals with a known object first: if("knownObject".equals(unknownObject)
  6. Prefer valueOf() over toString().
  7. Use null safe StringUtils methods StringUtils.isEmpty(null).

A null pointer exception is an indicator that you are using an object without initializing it.

For example, below is a student class which will use it in our code.

public class Student {

    private int id;

    public int getId() {
        return this.id;
    }

    public setId(int newId) {
        this.id = newId;
    }
}

The below code gives you a null pointer exception.

public class School {

    Student student;

    public School() {
        try {
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

Because you are using student, but you forgot to initialize it like in the correct code shown below:

public class School {

    Student student;

    public School() {
        try {
            student = new Student();
            student.setId(12);
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

In Java, everything (excluding primitive types) is in the form of a class.

If you want to use any object then you have two phases:

  1. Declare
  2. Initialization

Example:

  • Declaration: Object object;
  • Initialization: object = new Object();

Same for the array concept:

  • Declaration: Item item[] = new Item[5];
  • Initialization: item[0] = new Item();

If you are not giving the initialization section then the NullPointerException arise.

In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.

When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.

Your reference is "pointing" to null, thus "Null -> Pointer".

The object lives in the VM memory space and the only way to access it is using this references. Take this example:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

And on another place in your code:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.

Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.

String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object.

All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null.

You must initialize the elements in the array before accessing or dereferencing them.

String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top