Exceptions exist for a reason – use them! | John V. Petersen

:

C# and all CLR-compliant languages support a fantastic facility to ensuring code quality. That facility is the Exception. Sadly, it is an often under-utilized facility. How many times have you seen code that checks for an object’s validity? If, like me, you are part of the “Fail Early” school, then the Exception Class is your best friend. By fail early, I mean that as soon as possible, without any interaction from my code or any additional code, the system will abend. Of course, if your classes can throw exceptions, it means that your code will have to handle exceptions. Bear in mind that the try…catch block does come with an overhead cost that *may* impair performance. The key to look at is is what value are you getting for that cost? And – is whatever performance penalty there may be managed and negligible to the user.

It’s not enough to throw exceptions. Rather, you need to throw the right exception and in many cases, you’ll need to throw a custom exception. With a specific exception, you have a better chance of ascertaining exactly what happened. Only as a last resort will you want this:

   throw new Exception("Some other, unaccounted for exception");

Note: when possible, use the built-in exceptions that are already in .NET. For more detail on the base exceptions in .NET, refer to this link: http://msdn.microsoft.com/en-us/library/z4c5tckx(v=vs.110).aspx

Often you may want to create a custom exception:

    public class MyCustomException : Exception
    {
        public MyCustomException() : base("My Custom Exception")
        {

        }
    }

It’s worth noting in the constructor, you get access to many properties – some of which you may want to initialize:

The following is an example of an approach that you may wish to follow and adapt as necessary:

    public abstract class MyBaseException : Exception
    {
        public  MyBaseException(string message) : base(message)
        {
            HelpLink = "http://www.myhelplink.com/helptext";
            
        }

        public override string ToString()
        {

            return string.Format("{0}{1}{2}{3}", 
                base.ToString(),Environment.NewLine,
                "For more help on this error: ",HelpLink);

        }

        public void Log()
        {
            Console.WriteLine(ToString());
        }
    }

Note: In this particular example, no need to worry about serialization as there are no custom properties.

One of the nice things about the base Exception Class is that it has a usable ToString() method. Nevertheless, it is missing some additional information that could be useful. This is why there is an override for the ToString() method.

With a base exception class in place:

 try
            {
               throw new MyCustomException("My Custom Message");
            }
            catch (MyCustomException ex)
            {
                ex.Log();
            }

Here is the output:

exception_image2

Hopefully, this post has given you some ideas on how you can effectively use exceptions in your applications.