Pluralsight Logo
Author avatar

Peter Mbanugo

Author badge Author

Commonly Encountered Exceptions- ArgumentException, ArgumentNullException, and ArgumentOutOfRangeException

Peter Mbanugo

Author BadgeAuthor
  • Nov 7, 2018
  • 7 Min read
  • 7 Views
  • Nov 7, 2018
  • 7 Min read
  • 7 Views
C#

Introduction

An exception is a runtime error in a program that violates a system or application constraint, or a condition that is not expected to occur during normal execution of the program. Possible causes of exceptions include attempting to connect to a database that no longer exists when a program tries to divide a number by zero, or opening a corrupted XML file. When these occur, the system catches the error and raises an exception. Catching exceptions is a way of handling these unexpected errors by defining a block of code that will be run when an exception is thrown.

There are a few commonly encountered exception types that are useful to be aware of. In this guide, we will look at three of them. They are the ArgumentException exception type, the ArgumentNullException exception type, and the ArgumentOutOfRangeException exception type.

ArgumentException Type

The ArgumentException type is thrown when a method argument receives an invalid argument value. This exception type inherits from the System.SystemException class, which in turn derives from the System.Exception base class. The code below is a sample application that throws the ArgumentException type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter first name");
            var firstName = Console.ReadLine();

            Console.WriteLine("Enter last name");
            var lastName = Console.ReadLine();

            try
            {
                var fullName = GetFullName(firstName, lastName);
                Console.WriteLine($"Your fullname is {fullName}");
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Oh no, Something went wrong");
                Console.WriteLine(ex);
            }
        }

        static string GetFullName(string firstName, string lastName)
        {
            if (firstName == "" || lastName == "") throw new ArgumentException ("first & last name arguments cannot be empty");
            return $"{firstName} {lastName}";
        }
    }
}

The GetFullName method has two arguments, firstName and lastName, and it checks if either of the two is an empty string. If it evaluates either to be true, it throws an exception of type ArgumentException. We used the constructor that takes the exception message as the only parameter. The exception message we set above won't be very helpful in knowing which argument caused the exception. Wouldn't it be better if we can tell which argument caused the error, making it easier to fix the error?

The ArgumentException class has a ParamName property which identifies the invalid argument. This will be the name of the argument. With this knowledge, we can update the GetFullName method as follows.

1
2
3
4
5
6
7
static string GetFullName(string firstName, string lastName)
{
    if (firstName == "") throw new ArgumentException("empty string is an invalid value", "firstName");
    if (lastName == "") throw new ArgumentException("empty string is an invalid value", "lastName");

    return $"{firstName} {lastName}";
}

If you run the application and pass an empty string for the first name, you'll get the following error:

1
2
3
4
5
6
Oh no, Something went wrong

System.ArgumentException: empty string is an invalid value
Parameter name: firstName
   at MyApp.Program.GetFullName(String firstName, String lastName) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 30
   at MyApp.Program.Main(String[] args) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 17

You can see that it prints the exception message alongside the parameter name.

ArgumentNullException Type

The ArgumentNullException exception type derives from the ArgumentException class. This type of exception is thrown when a null value is passed to a method argument and null is not allowed for that argument. To illustrate, let's create a console application and update Program.cs with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var user = new User(null, 23);
            }
            catch (ArgumentNullException ex)
            {
                Console.WriteLine("Oh no, Something went wrong");
                Console.WriteLine(ex);
            }
        }

        class User
        {
            public User(string userName, int age)
            {
                if (userName == null)
                    throw new ArgumentNullException(nameof(userName), "username is invalid");

                UserName = userName;
                Age = age;
            }
            public string UserName { get; private set; }
            public int Age { get; private set; }
        }
    }
}

We define a User class with properties UserName and Age. In the class constructor we accept two parameters and assign them to the appropriate properties. Before the assignment, we check if userName is null. If it is, we throw an ArgumentNullException exception. We called the constructor of ArgumentNullException that accepts the parameter name that caused the exception and a second parameter representing the exception message. You might have noticed we used the nameof operator to get the string name of the parameter that caused the exception. Using nameof operator helps keep your code valid when renaming definitions.

If you run the application, it'll throw an exception because userName is null. It'll print the exception info in the console.

1
2
3
4
5
6
Oh no, Something went wrong

System.ArgumentNullException: username is invalid
Parameter name: userName
   at MyApp.Program.User..ctor(String userName, Int32 age) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 27
   at MyApp.Program.Main(String[] args) in /Users/pmbanugo/Documents/projects/dotnet/MyApp/Program.cs:line 11

ArgumentOutOfRangeException Type

The ArgumentOutOfRangeException type is a subclass of ArgumentException class. This exception type is thrown when the value of an argument is outside of the allowable range. For example, this can be thrown when you pass negative numbers to a function that accepts only positive numbers.

To demonstrate the usage of this type, we will continue with the sample application from the previous section. Edit the constructor of the User class as follows:

1
2
3
4
5
6
7
8
9
10
public User(string userName, int age)
{
    if (userName == null)
        throw new ArgumentNullException(nameof(userName), "username is invalid");
    if (age < 18 || age > 50)
        throw new ArgumentNullException(nameof(age), "age is outside the allowable range");

    UserName = userName;
    Age = age;
}

The code above throws an exception when the age argument is less than 18 or greater than 50.

Wrap Up

Exceptions can be thrown either by the runtime or the application code. This can be caused by bad code while, other times, the problem is caused by bad user input that has not been accounted for in the application’s code. In this guide, we looked at three commonly encountered exception types. They are ArgumentException, ArgumentNullException and ArgumentOutOfRangeException. They can be thrown by the common language runtime (CLR) or another class library and indicates developer error.

0