ArgumentNullException in .NET

In this article we will explain how we can handle the ArgumentNullException in .NET.
  • 3183

Introduction

Exception handling is very common in programs. Exceptions are used to indicate that an error has occurred while running the program. ArgumentNullException is thrown in case when a null reference is passed to a method that does not accept it as a valid argument. Computers can't handle this situation without using exception handling so its gives an error or Exception. This exception is called ArgumentNullException.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace application

{

    class MainClass

    {

        static void a(string s)

        {

            if (s == null)

            {

                throw new ArgumentNullException();

            }

        }

         static void Main()

        {

            try

            {

                string s = null;

                a(s);

            }          

            //catch (ArgumentNullException e)

            //{

            //    Console.WriteLine("{0} exception caught.", e);

            //}

                  catch (ArgumentNullException ex)

            {

                Console.WriteLine(ex);

                Console.WriteLine("HelpLink = {0}", ex.HelpLink);

                Console.WriteLine("Message = {0}", ex.Message);

                Console.WriteLine("Source = {0}", ex.Source);

                Console.WriteLine("StackTrace = {0}", ex.StackTrace);

                Console.WriteLine("TargetSite = {0}", ex.TargetSite);

            }

            finally

            {

                Console.WriteLine("Task completed");

            }

            Console.ReadLine();

        }

    }

}

The output of following program

 Clipboard106.jpg

© 2020 DotNetHeaven. All rights reserved.