#873 – Full Example of Throwing and Catching an Exception

Below is a complete example of throwing an exception from a method and catching/handling that exception further up the call stack.

Code for Dog class that throws an exception if we ask a dog to bark too many times:

    public class Dog
        public string Name { get; set; }
        public int Age { get; set; }

        // Dog constructor
        public Dog(string name, int age)
            Name = name;
            Age = age;

        // Dog.Bark
        public void Bark(int numTimes)
            if (numTimes > 10)
                throw new ArgumentException(
                    string.Format("{0} is just too many times to bark", numTimes));

            for (int i = 1; i <= numTimes; i++)

Code that calls the Bark method, with an exception handler in the Main() method:

        static void Main(string[] args)
                Console.WriteLine("Before MethodA call");
                Console.WriteLine("After MethodA call");
            catch (Exception xx)
                    string.Format("Caught in Main(): {0}",


        private static void MethodA()
            Console.WriteLine("Before MethodB call");
            Console.WriteLine("After MethodB call");

        private static void MethodB()
            Dog d = new Dog("Kirby", 15);
            Console.WriteLine("I barked 99 times");

Below is the output.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: