c# – Intro to Exceptions

Sometimes you might have a block of “dangerous code” in your program. These are code that could fail. When these blocks of “dangerous codes” fail, it will stop the program straight, and won’t attempt to carry on any further, and instead it will just output an error message.

However sometimes you might want your program to do some (or all) of the following when the “dangerous code” fails:

– continue with the rest of the program
– run a specific block of code when a failure occurs (aka error-handling)
– Customize the error message that get’s outputted.
– Create artificial error messages, that simulates a failure, when in fact, there is none. E.g. say you have a string variable called “FirstName”. A valid entry for this is “Mr”. However you want this to generate an error, because it looks like someone accidently entered their title in place of where there name is supposed to be (unless in the extremely rare occasion, a person has a first name of “Mr”).

Lets start of by looking at what happens when there is an ordinary error in the code.
In the following example, we have a class that contains the Main method. This main method calls FirstMethod, which in turn calls SecondMethod, which in turn calls ThirdMethod. I have also commented out the dangerous code to see what the output is when everything runs ok:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionExample
{
    class Program
    {
        static void Main(string[] args)
        {

            FirstMethod();

        }

        public static void FirstMethod()
        {
            Console.WriteLine("First Method Begins");
            SecondMethod();
            Console.WriteLine("First Method Ends");
        }

        private static void SecondMethod()
        {
            Console.WriteLine("Second Method Begins");
            ThirdMethod();
            Console.WriteLine("Second Method Ends");
        }

        private static void ThirdMethod()
        {
            Console.WriteLine("Third Method Begins");

            // The following line is the dangerous code, since we are trying ot
            // divide by zero!
            //int x = 0;
            //var y = 10 / x;
            Console.WriteLine("Third Method Ends");
        }

    }

}

This outputs:

Now if we enable the dangerous code and try again, we get:

As you can, this time the program grinds to a halt as soon as it encounters the error.

If you want the program to continue, and also run some error-handling, then this is where exception handling comes into play….via the use of the exception handling’s “try” and “catch” construct:

As you can see, that we got our custom error message, and also that the program didn’t crash/stop.

There is an extension to the try-catch construct, and that is the “finally” construct. This block of code runs regardless whether the try block passes or fails (causing the catch block to run). Here it is in action:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionExample
{
    class Program
    {
        static void Main(string[] args)
        {

            FirstMethod();

        }

        public static void FirstMethod()
        {
            Console.WriteLine("First Method Begins");
            SecondMethod();
            Console.WriteLine("First Method Ends");
        }

        private static void SecondMethod()
        {
            Console.WriteLine("Second Method Begins");
            ThirdMethod();
            Console.WriteLine("Second Method Ends");
        }

        private static void ThirdMethod()
        {
            Console.WriteLine("Third Method Begins");

            try
            {
                //The following line is the dangerous code, since we are trying to
                //divide by zero!
                int x = 0;
                var y = 10 / x;
            }
            catch (Exception ErrorObject)
            {
                Console.WriteLine("Third method failed with the following error message: " + ErrorObject.Message);

            }
            finally
            {
                Console.WriteLine("This code block alwaaaaaaaaays runs!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            }

            Console.WriteLine("Third Method Ends");
        }
    }
}

This will output:

You might wonder what is the point of the finally construct since the code after the try-catch construct will be executed anyway. The reasoning is that sometimes you might want to include some code at the end of the try-block, which you must always run. These code may fail to run if the try-block fails in midway, to cover that possibility, you would also add the same lines in the catch-block. However, then you will have ended up with the same lines of code in both blocks, i.e. we have duplicate lines of code. To overcome this, you take these codes out of both try-catch blocks and place them in the finally block.

However since the code after the catch-block are run anyway, then why bother with the catch block? That’s because there is a possibility that the catch block might also fail. In those instances, the “finally” block acts as the catch-block’s fail-safe.
Here’s an example where I intentionally placed an error in both the try and catch blocks:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionExample
{
    class Program
    {
        static void Main(string[] args)
        {

            FirstMethod();

        }

        public static void FirstMethod()
        {
            Console.WriteLine("First Method Begins");
            SecondMethod();
            Console.WriteLine("First Method Ends");
        }

        private static void SecondMethod()
        {
            Console.WriteLine("Second Method Begins");
            ThirdMethod();
            Console.WriteLine("Second Method Ends");
        }

        private static void ThirdMethod()
        {
            Console.WriteLine("Third Method Begins");

            try
            {
                //The following line is the dangerous code, since we are trying to
                //divide by zero!
                int x = 0;
                var y = 10 / x;
            }
            catch (Exception ErrorObject)
            {
                int x = 0;
                var y = 10 / x;
                Console.WriteLine("Third method failed with the following error message: " + ErrorObject.Message);

            }
            finally
            {
                Console.WriteLine("This code block alwaaaaaaaaays runs!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            }

            Console.WriteLine("Third Method Ends");
        }
    }
}

This outputs:

For more info see:

http://stackoverflow.com/questions/547791/why-use-finally-in-c