#865 – A catch Block Specifies the Type of Exception to Catch

In most cases, a catch block will specify the type of exception to intercept and catch.  Any exception occurring in the associated try block whose type matches the type indicated in the catch block will be caught.  Exceptions whose type is derived from the specified exception type will also be caught.

In the example below, we catch only exceptions of type FileNotFoundException, or of types that derive from this type. Other exception types will not be caught and will continue to bubble up the call stack.

            try
            {
                DoSomething();
                AskUserForFilename();
                DoSomethingElse();
            }
            catch (FileNotFoundException fnfExc)
            {
                Console.WriteLine(string.Format("Hey, we can't find file {0}!", fnfExc.FileName));
            }
Advertisements