ArgumentException in .NET

In this article we will explain how we can handle the ArgumentException in .NET.
  • 2051

Introduction

ArgumentException is thrown when one of the arguments provided to a method is not valid .Computers can't handle this situation without using exception handling so its gives an error or Exception.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace application

{

    class Program

    {

        static int Ma(string argument)

        {

          // Handle invalid argument.

            if (argument.Length == 0)

            {

                throw new ArgumentException("Zero-length string invalid", "argument");

            }

            return argument.Length;

        }

        static void Main()

        {

             // using try and catch block

            try

            {

                Ma("");

            }

            catch (Exception 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.ReadLine();

        }       

    }

}

The output of following program

 Clipboard107.jpg

ArgumentNullException and ArgumentOutOfRangeException is the derived class from ArgumentException. 

© 2019 DotNetHeaven. All rights reserved.