#915 – An Exception Can Cross Assembly Boundaries

If code within one assembly calls code within another assembly, exceptions originating within the code being called can bubble up to the calling code.  The exception can be thrown from one assembly and caught in another.

Below, code in the ConsoleApplication1 assembly calls code in the DogLibrary assembly (the Dog.Bark method).  When an exception originates in DogLibrary, we can catch it in the code running in ConsoleApplication1.

915-001

Code in ConsoleApplication1:

            try
            {
                Dog d = new Dog("Bowser");
                d.Bark(100);
            }
            catch (ApplicationException exc)
            {
                Console.WriteLine(exc.ToString());
            }

Code in DogLibrary:

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

        public Dog(string name)
        {
            Name = name;
        }

        public void Bark(int numTimes)
        {
            if (numTimes > 10)
                throw new ApplicationException("Too many times to bark");

            for (int i = 0; i < numTimes; i++)
                Console.WriteLine("Woof");
        }
    }

Catching an exception in ConsoleApplication1 that was thrown from DogLibrary:
915-002