logo

Eccezione puntatore null in Java

In questo tutorial impareremo l'eccezione del puntatore Null in Java. L'eccezione del puntatore null è un'eccezione di runtime. Null è un tipo speciale di valore che può essere assegnato al riferimento di un oggetto. Ogni volta che si tenta di utilizzare un riferimento che ha il valore Null, viene sollevata la NullPointerException.

Diversi scenari per l'eccezione del puntatore nullo

Osservare alcuni dei seguenti scenari in cui è possibile sollevare NullPointerException.

  • Calcolare la dimensione o la lunghezza del Null come se fosse un array di elementi.

Nome del file: ThrowNullExcep.java

 public class ThrowNullExcep { // main method public static void main(String args[]) { int arr[] = null; // array is assigned a null value System.out.println('The length of the array arr is: ' + arr.length); } } 

Produzione:

Eccezione nel thread 'main' java.lang.NullPointerException: impossibile leggere la lunghezza dell'array perché '' è null in ThrowNullExcep.main(ThrowNullExcep.java:7)
  • Chiamare un metodo utilizzando l'oggetto che ha il valore Null.

Nome del file: ThrowNullExcep1.java

Rajesh Khanna
 public class ThrowNullExcep1 { public void foo() { System.out.println('In the method foo.'); } public static void main(String args[]) { ThrowNullExcep1 obj = null; // assigning null value // invoking the method foo() obj.foo(); } } 

Produzione:

 Exception in thread 'main' java.lang.NullPointerException: Cannot invoke 'ThrowNullExcep1.foo()' because '' is null at ThrowNullExcep1.main(ThrowNullExcep1.java:13) 
  • Quando provi a sincronizzarti su un oggetto NULL.

Nome del file: ThrowNullExcep2.java

 // A Java program that synchronizes over a NULL object. import java.util.*; import java.io.*; // A Class that is required for sending the message class Sendr { public void sendMethod(String mssg) { System.out.println('Sending message: ' + mssg ); try { Thread.sleep(100); } catch (Exception exp) { System.out.println('Thread interrupted.' + exp); } System.out.println('
' + mssg + ' is sent'); } } // A Class that is used to send messages with the help of threads Threads class ThreadSend extends Thread { private String mssg; Sendr sendr; // Received a messge obj and the string // mssge that has to be sent ThreadSend(String mStr, Sendr obj) { mssg = mStr; sendr = obj; } public void run() { // Only a single thread is allowed to send a message // at a time. synchronized(sendr) { // synchronizing the send object sendr.sendMethod(mssg); } } } // Driver class public class ThrowNullExcep2 { // main method public static void main(String args[]) { Sendr sendObj = null; ThreadSend Sth1 = new ThreadSend( ' Hello ' , sendObj ); ThreadSend Sth2 = new ThreadSend( ' Bye Bye ' , sendObj ); // Starting the two threads of the ThreadedSend type Sth1.start(); Sth2.start(); // waiting for the threads to end try { Sth1.join(); Sth2.join(); } catch(Exception exp) { System.out.println('Interrupted : ' + exp); } } } 

Produzione:

 Exception in thread 'Thread-0' Exception in thread 'Thread-1' java.lang.NullPointerException: Cannot enter synchronized block because 'this.sendr' is null at ThreadSend.run(ThrowNullExcep2.java:42) java.lang.NullPointerException: Cannot enter synchronized block because 'this.sendr' is null at ThreadSend.run(ThrowNullExcep2.java:42) 
  • Invece di lanciare un valore, viene lanciato Null.

Nome del file: ThrowNullExcep3.java

gimp sostituisce il colore
 // Modifying or accessing the fields of the Null object. public class ThrowExcep3 { int a; // main method public static void main(String args[]) { // assigning a null value ThrowExcep3 obj = null; obj.a = 3; } } 

Produzione:

 Exception in thread 'main' java.lang.NullPointerException: Cannot assign field 'a' because '' is null at ThrowExcep3.main(ThrowExcep3.java:10) 

Requisito di valore NULL

Un null è un valore speciale utilizzato in Java. Di solito viene utilizzato per mostrare che non esiste alcun valore assegnato alla variabile di riferimento. Un valore null viene utilizzato principalmente nell'implementazione di strutture dati come un elenco collegato o un albero. Viene utilizzato anche nel modello Singleton.

Evitare la NullPointerException

Per evitare la NullPointerException, è necessario assicurarsi che l'inizializzazione di tutti gli oggetti sia eseguita correttamente prima di poterli utilizzare. Quando si dichiara una variabile di riferimento, è necessario verificare che il valore null non sia assegnato al riferimento prima che il valore di riferimento venga utilizzato per accedere al campo o al metodo.

Osservare i seguenti problemi comuni con la soluzione.

Caso 1: Confronto di stringhe con il letterale

Uno dei problemi più comuni include il confronto di un valore letterale con una variabile String. Il letterale può essere un elemento di un Enum o di una String. Invece di invocare il metodo dall'oggetto null, considera di invocarlo utilizzando il valore letterale.

esempi di programmazione Python

Nome del file: NullPntrExcption.java

 import java.io.*; public class NullPntrExcption { // main method public static void main (String[] args) { // Initializing a String variable with a null value String pntr = null; // Checking if pntr.equals null or works fine. try { // The following line of code will raise the NullPointerException // It is because the pntr is null if (pntr.equals('JTP')) { System.out.print('String are the same.'); } else { System.out.print('Strinng are not the same.'); } } catch(NullPointerException e) { System.out.print('NullPointerException has been caught.'); } } } 

Produzione:

 NullPointerException has been caught. 

Ora vediamo come evitarlo.

Nome del file: NullPntrExcption1.java

converti la stringa int java
 public class NullPntrExcption1 { // main method public static void main (String[] args) { // Initializing a String variable with a null value String pntr = null; // Checking if pntr.equals null or works fine. try { // Now, the following line of code will not raise the NullPointerException // It is because the string literal is invoking the equals() method if ('JTP'.equals(pntr)) { System.out.print('String are the same.'); } else { System.out.print('Strinng are not the same.'); } } catch(NullPointerException e) { System.out.print('NullPointerException has been caught.'); } } } 

Produzione:

 NullPointerException has been caught. 

Caso 2: Tenendo d'occhio gli argomenti del metodo

È necessario prima controllare gli argomenti del metodo per i valori nulli e poi procedere con l'esecuzione del metodo. Altrimenti, ci sono buone possibilità che lanci una IllegalArgumentException e segnali anche al metodo chiamante che è sbagliato con gli argomenti che sono stati passati.

tabella desc in mysql

Nome del file: NullPntrExcption2.java

 // A program for demonstrating that one must // check the parameters are null or not before // using them. import java.io.*; public class NullPntrExcption2 { public static void main (String[] args) { // String st is an empty string and invoking method getLength() String st = ''; try { System.out.println(getLength(st)); } catch(IllegalArgumentException exp) { System.out.println('IllegalArgumentException has been caught.'); } // String s set to a value and invoking method getLength() st = 'JTP'; try { System.out.println(getLength(st)); } catch(IllegalArgumentException exp) { System.out.println('IllegalArgumentException has been caught.'); } // Setting st with a value null and invoking method getLength() st = null; try { System.out.println(getLength(st)); } catch(IllegalArgumentException exp) { System.out.println('IllegalArgumentException has been caught. ' + exp); } } // method taht computes the length of a string st. // It throws and IllegalArgumentException, if st is null public static int getLength(String st) { if (st == null) { throw new IllegalArgumentException('The argument can never be null.'); } return st.length(); } } 

Produzione:

 0 3 IllegalArgumentException has been caught. java.lang.IllegalArgumentException: The argument can never be null. 

Caso 3: Utilizzo dell'operatore ternario

Si può anche usare l'operatore ternario per evitare la NullPointerException. In ternario, l'espressione booleana viene valutata per prima. Se l'espressione viene valutata come vera, viene restituito val1. Altrimenti, viene restituito val2.

Nome del file: NullPntrExcption3.java

 // A program for demonstrating the fact that // NullPointerException can be avoided using the ternary operator. import java.io.*; public class NullPntrExcption3 { // main method public static void main (String[] args) { // Initializing String variable with null value String st = null; String mssge = (st == null) ? 'String is Null.' : st.substring(0, 5); System.out.println(mssge); // Initializing the String variable with string literal st = 'javaTpoint'; mssge = (st == null) ? '' : st.substring(0, 10); System.out.println(mssge); } } 

Produzione:

 String is Null. javaTpoint