#889 – Catching Exceptions that Derive from a Common Base Type

When you specify an exception type to catch in a handler, the handler will catch all exceptions whose type matches the specified type.  It will also catch exceptions where the exception object’s type is a type that derives from the specified type.

In the example below, we catch exceptions of type System.ArgumentException.  This handler will catch exceptions where the exception object’s type is:

  • ArgumentException
  • ArgumentNullException  (derives from ArgumentException)
  • ArgumentOutOfRangeException  (derives from ArgumentException)
  • Any custom exception types you define that derive from ArgumentException or from one of its child classes
  • Various other exception types in the Framework that derive from ArgumentException
            try
            {
                Dog d = new Dog("Bob", 3);
                d.Bark();
            }
            catch (ArgumentException exc)
            {
                Console.WriteLine("You've got a problem with an argument");
                Console.WriteLine(exc.Message);
            }

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

Leave a comment