Custom Exceptions

The intrinsic exception types C# provides, coupled with the custom messages shown in the previous example, will often be all you need to provide extensive information to a catch block when an exception is thrown.

Sometimes, however, you will want to provide more extensive information or need special capabilities in your exception. It is a trivial matter to create your own custom exception class. Even though you’ll rarely need to do it, Example 16-7 illustrates the creation of a custom exception.

Example 16-7. Although C# provides a range of exceptions that you’ll use most of the time, you can define a custom exception if you need it

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

namespace Example_16_7_ _ _ _Custom_Exception
{
    // custom exception class
    public class MyCustomException : System.Exception
    {
        public MyCustomException(string message) :
            base(message) // pass the message up to the base class
        {
        }
    }

    class Tester
    {
        public void Run()
        {
            try
            {
                Console.WriteLine("Open file here");
                double a = 0;
                double b = 5;
                Console.WriteLine("{0} / {1} = {2}", a, b,
                                  DoDivide(a, b));
                Console.WriteLine("This line may or may not print");
            }

            // most derived exception type first
            catch (System.DivideByZeroException e)
            {
                Console.WriteLine("
DivideByZeroException! Msg: {0}",
                                  e.Message);
                Console.WriteLine("
HelpLink: {0}
", e.HelpLink);
            }
            // catch custom exception
            catch (MyCustomException e)

            {
                Console.WriteLine("
MyCustomException! Msg: {0}",
                                  e.Message);
                Console.WriteLine("
HelpLink: {0}
", e.HelpLink);
            }
            catch // catch any uncaught exceptions
            {
                Console.WriteLine("Unknown exception caught");
            }
            finally
            {
                Console.WriteLine("Close file here.");
            }
        }

        // do the division if legal
        public double DoDivide(double a, double b)
        {
            if (b == 0)
            {
                DivideByZeroException e = new DivideByZeroException();
                e.HelpLink = "http://www.libertyassociates.com";
                throw e;
            }
            if (a == 0)
            {
                // create a custom exception instance
                MyCustomException e = new MyCustomException("Can't
                                      have zero dividend");
                e.HelpLink =
                 "http://www.libertyassociates.com/NoZeroDividend.htm";
                throw e;
            }
            return a / b;
        }

        static void Main()
        {
            Console.WriteLine("Enter Main...");
            Tester t = new Tester();
            t.Run();
            Console.WriteLine("Exit Main...");
        }
    }
}

The output looks like this:

Enter Main...
Open file here

MyCustomException! Msg: Can't have zero dividend


HelpLink: http://www.libertyassociates.com/NoZeroDividend.htm

Close file here.
Exit Main...

MyCustomException is derived from System.Exception and consists of nothing more than a constructor that takes a string message that it passes to its base class. There’s no code inside the constructor at all.

The advantage of creating this custom exception class is that it better reflects the particular design of the Tester class. That is, you’ve decided that, for whatever reason, it’s not legal to have a zero dividend in this class.

Using the ArithmeticException rather than a custom exception would work as well, but it might confuse other programmers because a zero dividend wouldn’t normally be considered an arithmetic error. Using a custom exception indicates that the exception was raised because of a violation of rules that are particular to your class.

You are free, of course, to add methods and properties to your custom exception classes as needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset