How to capture null reference exception in C#?



It handles errors generated from referencing a null object. The Null reference exception occurs when you are looking to access member fields or function types that points to null.

Let’s say we have the following null string −

string str = null;

Now you try to get the length of the null string, then it would cause an exception −

If(str.Length == null) {}

Above the exception will be thrown. Now let us seen how to prevent the null pointer exception to be thrown −

Example

 Live Demo

using System; class Program {    static void Main() {       int[] arr = new int[5] {1,2,3,4,5};       display(arr);       arr = null;       display(arr);    }    static void display(int[] arr) {       if (arr == null) {          return;       }       Console.WriteLine(arr.Rank);    } }

Output

1
Updated on: 2020-06-20T14:54:23+05:30

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements