Lesson 10 – Exception Handling in C#

Exceptions are errors that halt the otherwise normal program execution. A C# program can have two types of errors: compile-time errors and runtime errors. Runtime errors are also known as exceptions. A missing semi-colon is a perfect example of a compile-time error. The good thing about compile-time errors is that they can be caught before the execution of a program. On the other hand, exceptions are not caught before program execution, rather they occur at runtime. For instance, division of a number by zero, or assignment of value at an array index which doesn’t exist can result in an exception.

Exception Example

Let’s see a simple example of an exception where we try to access an array index which doesn’t exist:

using System;

namespace C_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            string [] weeks = new string [6];
            weeks[10] = "Monday";
        }

    }

}

In the script above, the “weeks” array has 7 indexes. We try to access the 11th index which doesn’t exist, you should see the following exception when you run the above script:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Handling Exceptions

To handle an exception, you simply have to wrap the code that is likely to through exception, inside the “try” block. You also need to add a “catch” block. In case if the exception occurs, instead of crashing the application the “catch” block will execute. You can display an error message to the user using the “catch” block as shown below:

using System;

namespace C_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string[] weeks = new string[6];
                weeks[10] = "Monday";
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

    }

}

Now, when you run the above code, the program wont crash and you will see the following message on the console:

Index was outside the bounds of the array.

What’s Next?

With this, we end this introductory course on C#. I would suggest that the knowledge that you gained in this course should be used as a foundation to learn web, mobile, and desktop application development with C#.