logo

Izjema ničelnega kazalca v Javi

V tej vadnici se bomo naučili izjeme ničelnega kazalca v Javi. Izjema ničelnega kazalca je izjema med izvajanjem. Null je posebna vrsta vrednosti, ki jo je mogoče dodeliti sklicu predmeta. Kadar koli poskušate uporabiti sklic, ki ima vrednost Null, se sproži izjema NullPointerException.

Različni scenariji za izjemo ničelnega kazalca

Upoštevajte nekaj naslednjih scenarijev, kjer je mogoče sprožiti NullPointerException.

  • Izračunavanje velikosti ali dolžine Null, kot da bi bil niz elementov.

Ime datoteke: 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); } } 

Izhod:

Izjema v niti 'main' java.lang.NullPointerException: ni mogoče prebrati dolžine matrike, ker je '' nič pri ThrowNullExcep.main(ThrowNullExcep.java:7)
  • Klicanje metode z uporabo predmeta, ki ima vrednost Null.

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

Izhod:

 Exception in thread 'main' java.lang.NullPointerException: Cannot invoke 'ThrowNullExcep1.foo()' because '' is null at ThrowNullExcep1.main(ThrowNullExcep1.java:13) 
  • Ko poskušate sinhronizirati prek predmeta NULL.

Ime datoteke: 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); } } } 

Izhod:

 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) 
  • Namesto vrženja vrednosti se vrže vrednost Null.

Ime datoteke: 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; } } 

Izhod:

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

Zahteva vrednosti NULL

Nič je posebna vrednost, ki se uporablja v Javi. Običajno se uporablja za prikaz, da referenčni spremenljivki ni dodeljene vrednosti. Ničelna vrednost se večinoma uporablja pri izvajanju podatkovnih struktur, kot je povezan seznam ali drevo. Uporablja se tudi v vzorcu Singleton.

Izogibanje izjemi NullPointerException

Da bi se izognili izjemi NullPointerException, je treba zagotoviti, da je inicializacija vseh predmetov izvedena pravilno, preden jih lahko uporabimo. Ko nekdo deklarira referenčno spremenljivko, mora preveriti, da sklicu ni dodeljena ničelna vrednost, preden se referenčna vrednost uporabi za dostop do polja ali metode.

Upoštevajte naslednje pogoste težave z rešitvijo.

1. primer: Primerjava nizov z literalom

Ena od pogostih težav vključuje primerjavo literala s spremenljivko String. Literal je lahko element iz enuma ali iz niza. Namesto da prikličete metodo iz ničelnega objekta, razmislite o tem, da bi jo priklicali z uporabo literala.

Ime datoteke: 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.'); } } } 

Izhod:

 NullPointerException has been caught. 

Zdaj pa poglejmo, kako se temu lahko izognemo.

Ime datoteke: 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.'); } } } 

Izhod:

 NullPointerException has been caught. 

2. primer: Pazi na argumente metode

Najprej je treba preveriti argumente metode za ničelne vrednosti in nato začeti z izvajanjem metode. V nasprotnem primeru obstaja precejšnja verjetnost, da bo vrgel IllegalArgumentException in bo klicni metodi tudi sporočil, da je napačna s posredovanimi argumenti.

Ime datoteke: NullPntrExcption2.java

java niz vsebuje
 // 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(); } } 

Izhod:

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

Primer 3: Uporaba ternarnega operaterja

Uporabite lahko tudi ternarni operator, da se izognete izjemi NullPointerException. V ternarnem se najprej ovrednoti logični izraz. Če je izraz ovrednoten kot resničen, se vrne val1. V nasprotnem primeru je vrnjen val2.

Ime datoteke: 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); } } 

Izhod:

 String is Null. javaTpoint