logo

Wyjątek wskaźnika zerowego w Javie

W tym samouczku nauczymy się wyjątku wskaźnika zerowego w Javie. Wyjątek wskaźnika zerowego jest wyjątkiem w czasie wykonywania. Null to specjalny rodzaj wartości, którą można przypisać do odniesienia do obiektu. Za każdym razem, gdy ktoś próbuje użyć odwołania o wartości Null, zgłaszany jest wyjątek NullPointerException.

Różne scenariusze wyjątku wskaźnika zerowego

Obserwuj niektóre z poniższych scenariuszy, w których można zgłosić wyjątek NullPointerException.

alfabet liczb
  • Obliczanie rozmiaru lub długości wartości Null tak, jakby była to tablica elementów.

Nazwa pliku: 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); } } 

Wyjście:

Wyjątek w wątku „main” java.lang.NullPointerException: Nie można odczytać długości tablicy, ponieważ „” ma wartość null w ThrowNullExcep.main(ThrowNullExcep.java:7)
  • Wywołanie metody przy użyciu obiektu, który ma wartość Null.

Nazwa pliku: ThrowNullExcep1.java

 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(); } } 

Wyjście:

 Exception in thread 'main' java.lang.NullPointerException: Cannot invoke 'ThrowNullExcep1.foo()' because '' is null at ThrowNullExcep1.main(ThrowNullExcep1.java:13) 
  • Podczas próby synchronizacji przez obiekt NULL.

Nazwa pliku: 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); } } } 

Wyjście:

 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) 
  • Zamiast rzucać wartość, rzucany jest Null.

Nazwa pliku: ThrowNullExcep3.java

 // 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; } } 

Wyjście:

tablica struktur w języku c
 Exception in thread 'main' java.lang.NullPointerException: Cannot assign field 'a' because '' is null at ThrowExcep3.main(ThrowExcep3.java:10) 

Wymaganie wartości NULL

Wartość null to specjalna wartość używana w Javie. Zwykle służy do pokazania, że ​​do zmiennej referencyjnej nie jest przypisana żadna wartość. Wartość null jest używana głównie w implementacji struktur danych, takich jak połączona lista lub drzewo. Jest również używany we wzorze Singleton.

Unikanie wyjątku NullPointerException

Aby uniknąć wyjątku NullPointerException, należy upewnić się, że inicjalizacja wszystkich obiektów została wykonana prawidłowo, zanim będzie można z nich skorzystać. Kiedy deklaruje się zmienną referencyjną, należy sprawdzić, czy wartość null nie jest przypisana do referencji, zanim wartość referencyjna zostanie użyta w celu uzyskania dostępu do pola lub metody.

Zapoznaj się z poniższymi typowymi problemami i znajdź rozwiązanie.

Przypadek 1: Porównanie ciągów znaków z literałem

Jednym z typowych problemów jest porównanie literału ze zmienną typu String. Literał może być elementem wyliczenia lub ciągu znaków. Zamiast wywoływać metodę z obiektu null, rozważ wywołanie jej za pomocą literału.

Nazwa pliku: 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.'); } } } 

Wyjście:

 NullPointerException has been caught. 

Zobaczmy teraz, jak można tego uniknąć.

Nazwa pliku: NullPntrExcption1.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.'); } } } 

Wyjście:

 NullPointerException has been caught. 

Przypadek 2: Obserwuj argumenty metody

Należy najpierw sprawdzić argumenty metody pod kątem wartości null, a następnie przystąpić do wykonywania metody. W przeciwnym razie istnieje spore prawdopodobieństwo, że zgłosi wyjątek IllegalArgumentException, a także zasygnalizuje metodzie wywołującej, że jest ona nieprawidłowa z przekazanymi argumentami.

Nazwa pliku: 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(); } } 

Wyjście:

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

Przypadek 3: Użycie operatora trójskładnikowego

Można również użyć operatora trójskładnikowego, aby uniknąć wyjątku NullPointerException. W przypadku trójskładnikowym najpierw oceniane jest wyrażenie logiczne. Jeśli wyrażenie zostanie ocenione jako prawdziwe, zwracana jest wartość val1. W przeciwnym razie zwracana jest wartość val2.

Nazwa pliku: NullPntrExcption3.java

przeczytaj plik csv w Javie
 // 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); } } 

Wyjście:

 String is Null. javaTpoint