Null Pointer Exception in C#


NullReferenceException is a C# version of NullPointerException. To handle and catch it in C#, use try-catch.

The below example shows that a variable is set to null and when we try to print it, it throws an exception that gets caught in the catch −

Try {
   a = null;
   Console.WriteLine(a);
}catch (NullPointerException ex) {
   Console.WriteLine("Variable is Null!");
}

The above will allow the exception to be caught and use catch for it.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 21-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements