Click here to Skip to main content
15,886,362 members
Articles / All Topics

What Is A Null Error in Code Execution

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
4 Nov 2014MIT5 min read 31.3K   2  
null error in code execution

In my past few years of experience in coding, many times, I have faced the exception for passing on Null values. Due to which, the compiler or the machine throws this exception out to the screen.

C#
System.NullReferenceException

Actually, many times, this case has been discussed by other professional developers and part-time developers and they’ve provided the solution to this many times that I think, if you just close your eyes and go for the solution, you’ll find it on the very 3rd web page for the tutorial websites.

System.NullReferenceException is the exception raised when you try to dereference a null object. Read the post for more information on that.

What Actually Is This Error?

This error occurs when you’re passing on a null value. A null value means that there is actually no value in this variable. It's not even a zero. String is the major case for this exception because other variables sometimes get a zero value, and hide this error. Arrays give out this error, when they’re empty. So in general, anything that has no value, is called to have a null value.

Null means that the object doesn't exist.
Null means that the object doesn’t exist.

If you read this MSDN post, you will get the understanding of the concept of null, how they’re created in programming, how they’re a cause of an error in programming.

Why Does This Error Come Up?

This error generally comes up when you’re trying to pass a null value as an argument (parameter) to a method (function) that needs an active parameter to work on. When the parameter being passed is empty, null it throws this error telling the developer that the variable that he passed is zero.

You can take the example of a shopkeeper. You ask him to give you a packet of biscuits, but you don’t pay him. What would he do? He’d shout at you like, ‘Hey, you didn’t pay for the biscuits!’. This thing is exactly like that. You don’t pass any value and the compiler complains to you in this manner, telling you that you’ve provided him with nothing.

In programming, many functions or properties accept an argument to work on. For example, take an example of the following code:

C#
int myVar = null;

// use the myVar in some methods etc

Once this code executes, the myVar is more likely to raise the NullReferenceException in your program execution.

Example of NullReferenceException being raised.
Example of NullReferenceException being raised in an application. Object reference not set to an instance of object means that the reference does not exist.

Empty lists, empty strings are an example of objects that might trigger a null reference exception in your software applications.

How To Handle This Error?

There are many ways of doing this. You can either use a try catch block to see what is the error and then handle it. You can either use a simple condition operator (if else, in this scenario) to detect the value and then do respectively. Or you can use your own idea to check the value is not null. Or you can even prompt the user to enter the value, otherwise don’t trigger the function at all. Or…you can do anything.

Usually, you handle all type of exceptions in your software, to minimize any possible condition that would stop the program execution and would break the application causing a bad user experience.

Here are a few samples for that.

Using a Try Catch Block

A try catch block is a simple block of code, which executes a block of code in the try part and if there is an error in the code, it passes that error to the catch block for the developer to handle it in a user friendly manner.

C#
try 
{
   // your source code here...
   // that would trigger the exception
} 
catch (System.NullPointerException e) 
{
   Console.Write("There was a raised error in your code.");
}

In the above example, the catch block would execute if the variable being used was empty. If there would have been some value, the array would have value thus preventing the error. Somehow, even if there is an error in your code, the application won’t break but will show an error message to the user. Which is helpful for creating enterprise software, where software loads a lot of data before creating the UI and loading to let the user start using it.

This MSDN post shows the concept of a try catch structure in programming.

Flowchart for a try catch structure is as follows:

Exceptions are only caught using try catch block.
Exceptions are only caught using try catch block.

if else Block

This block is the basic block of the conditional operation. It checks for a value, and executes either one depending on the true or false result of a condition. It is pretty handy and short for those who don’t have to work with errors, but just with values and condition.

C#
if(something != null) { // check for value null
  Console.Write("Not null! String is " + something);
} else {
  Console.Write("Whoops! Null exception.");
}

See, this was pretty easy to handle. Using this structure, you allow the user to do whatever he wants to do. But you move down to the critical stages only if the user has provided enough details for the software to work on.

This if else block checks for the value, if the condition is met (the value is provided), then it will execute the code, otherwise the second block of code would be executed.

Still remember, that if else blocks do not prevent any error chances if just checks for the value. It is not a good approach to minimize the null reference exception using an if else block. But programmers usually use it instead of try catch. But the best method of catching exceptions of any kind is to use the try catch block. It allows you to capture all of the exceptions that are raised in the application and do programming according.

This MSDN post explains if else structure.

Flowchart for if else block is as:

If else is just used to check a condition.
If else is just used to check a condition.

Remedies

Now there are some other ideas and logic to work with the code and prevent this error from happening. One of them is to always ask for the value and then continue, if user doesn’t provide the value, keep him prompted that once he adds value, only then can he use that particular feature and all that stuff. Otherwise, just to prevent the error, don’t show stuff to the user.

For example, the following UI is useful to get the values from the user. Until he doesn’t provide any value, either continue to how that error message or just try to disable any button or control that would trigger the function to get the values from the controls and work on them.

Disabling the Button is a better User Experience as compared to showing an Alert Box. Always look for the better UX.
Disabling the Button is a better User Experience as compared to showing an Alert Box. Always look for the better UX.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
-- There are no messages in this forum --