Saturday 12 September 2015

Throw Exceptions

In our development there comes a time when we have to throw exceptions from our objects to communicate that there was a problem, for example if we have an object that has a problem, that object shouldn't really handle it, they should just let the consumer that something is wrong and let the consumer deal with it.


using System.Text.RegularExpressions;

namespace pc.exceptionThrowing
{
    class Person
    {
        private string _firstName = "";
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = CheckName(value);
            }
        }

        private string _lastName = "";
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = CheckName(value); }
        }

        private string CheckName(string value)
        {
            if (Regex.IsMatch(value, @"^[a-zA-Z]{2,}$"))
                return value;
            throw new FormatException($"{value} is not a valid name");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var p = new Person { FirstName = "Pawel", LastName = "Cicui2as" };
            }
            catch (FormatException ex) {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


In the above example, we create a person class, and when we set the properties we test to see if the values provided are valid, and we throw a format exception if they're not. Our main program then catches those exceptions and handles them. It's important to understand that when an exception is thrown, the normal flow of the program is disrupted, any code after the throw statement will not be executed. It's a best practice to throw an exception as soon as you detect an error, rather than trying to continue executing the method and risk causing further problems, this also simplifies troubleshooting your code, the closer the exception is to the problem the easier it is to debug.

Keep in mind that exceptions should only be thrown in exceptional cases, as they carry some performance overhead. That is not to say that you shouldn't use, but just don't use them for logical flow... because that would be terrible.