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
1
2
3
4
5
6
7
8
9
10
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);
}