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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
    }
 
    // <span class="skimlinks-unlinked">Dog.Bark</span>
    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++)
            Console.WriteLine("Woof");
    }
}
Code that calls the Bark method, with an exception handler in the Main() method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
static void Main(string[] args)
{
    try
    {
        Console.WriteLine("Before MethodA call");
        MethodA();
        Console.WriteLine("After MethodA call");
    }
    catch (Exception xx)
    {
        Console.WriteLine(
            string.Format("Caught in Main(): {0}",
                          xx.Message));
    }
 
    Console.ReadLine();
}
 
private static void MethodA()
{
    Console.WriteLine("Before MethodB call");
    MethodB();
    Console.WriteLine("After MethodB call");
}
 
private static void MethodB()
{
    Dog d = new Dog("Kirby", 15);
    d.Bark(99);
    Console.WriteLine("I barked 99 times");
}


Below is the output.
873-001