Understanding Null Pointer Exception
An exception in programming is an event that is triggered when a problem or an issue arises during compilation or execution of that program. Exceptions prompt the developers at compile time or runtime that a solution to a particular programming problem has not been handled. Developers should handle the scenario before shipping the product to the end customers. There are two types of exceptions: a compile time exception often referred to as syntax errors and a runtime exceptions that are logic errors.
Compile Time vs. Run Time Exceptions
Compile time exceptions occur during code compilation. These exceptions are not critical since they can be handled before a program has been compiled and shipped to the customer. A typical example of a compile time exception is a missing bracket. The compiler or the IDE prompts the developer that a bracket is missing and should be inserted. The code is never compiled unless a bracket is inserted. On the contrary, runtime exceptions are critical and cannot be caught at compile time. They crash the program at run time if they are not handled. For instance, if a number is divided by zero at run time, a DivideByZeroException is thrown at runtime. This exception was not caught at runtime, because the compiler doesn’t know beforehand that a number is going to be divided by zero.
Another extremely important runtime exception is the Null Pointer Exception, which you need to thoroughly comprehend for proper planning and error handling.
To learn more about exceptions in Java, take a course at Udemy.com.
What is Null Pointer Exception?
In object-oriented programming, when a class is instantiated, its object is stored in computer memory. To refer to this object and to use it in a program requires a reference variable of the type of the class that has an object has to be instantiated. This reference variable actually points to a memory address of the object. To call the methods of that object and to access the properties and fields of that class, this reference variable is used. Null pointer exception occurs when a reference variable of the object contains a null value and that object is used for calling methods or instance variables.
How Null Pointer Exception occurs?
For the sake of explanation, a null pointer exception has been explained with the help of Java code and C# code; two of the most widely object-oriented languages. A null pointer exception also occurs in C and C++ where actual pointers are used to point to memory locations. The following example demonstrates how a null pointer exception actually occurs in Java and C#.
Java Code:
Suppose, there is a class named Person. The definition of the Person class is as follows:
public class Person { public int age= 10; public String name; public int getAge() { returnage; } public void setAge(int age) { this.age = age; } }
Now, if the Person class is instantiated by calling its constructor, the object of the Person class will be created in computer memory and a reference to that object will be returned to the instance reference variables. The following example demonstrates this concept:
Person p = new Person(); System.out.println (p.getAge());
In the above example, the variable p of type Person points to the memory address of the object of the person class. Now, getAge method is called, a value of 10 is printed on screen, which is the value of the member variable age.
Now, if p is somehow made to point at null reference by assigning a value of null to it via null keyword and then same p.getAge method is called on it, the compiler doesn’t generate any error, however if the code is executed it will crash at the location where the getAge method is called on reference variable p since it will be pointing to null. For instance if the following code is executed, null pointer exception will occur:
p = null; System.out.println (p.getAge());
The output of the above code will be:
Exception in thread “main” java.lang.NullPointerException
This error message shows that an exception of type NullPointerException that belongs to the java.lang package has occurred. Exceptions in Java are treated as classes.
C# Code:
The following example demonstrates the C# version of the example that was used to explain null pointer exception in Java.
class Person { public int age = 10; public string name; public int GetAge() { return age; } public void SetAge(int age) { this.age = age; } } class Program { static void Main(string[] args) { Person p = new Person(); Console.WriteLine(p.GetAge()); Console.ReadLine(); } } }
In the class program above, if p is made to point to null and then again the GetAge method is called on instance variable p, a null pointer exception will occur and a message will be displayed that a NullReferenceException was unhandled. NullReferenceException is a C# version of NullPointerException.
Interested in learning more about exceptions in C#? Take a course at Udemy.com.
Handling Null Pointer Exception
There are two ways to handle, null pointer exceptions. First ways is that make sure that a reference variable is not pointing towards a null reference, before using it. This is demonstrated in the following example:
if(p !=null) System.out.println (p.getAge()); else System.out.println ("Age cannot be retrieved, variable is poiting to null");
This looks tedious, since p variable has to be checked for null value before it is used. A better approach is to use a try and catch block. This is demonstrated in the following example:
try { System.out.println (p.getAge()); p = null; System.out.println (p.getAge()); } catch (NullPointerException ex) { System.out.println ("Age cannot be retrieved, variable is poiting to null"); }
Any piece of code that is likely to throw an exception is encapsulated in the try block and the code that should execute when an exception occurs is encapsulated in the catch block. Multiple catch blocks can be used for one try block to add a particular type of exception for instance in above example, the catch block will catch all NullPointerException. A try block is always followed immediately by the catch block.
For more on exceptions in Java, look at a course at Udemy.com.
Recommended Articles
Top courses in Java
Java students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.