#867 – Including Several catch Blocks

You can include several catch blocks in a single try-catch statement, each catch block set up to catch a different kind of exception.

            try
            {
                DoSomething(5);
            }
            catch (FileNotFoundException noFileExc)
            {
                Console.WriteLine(string.Format("File Not Found: {0}", noFileExc.FileName));
            }
            catch (ArgumentOutOfRangeException argExc)
            {
                Console.WriteLine("Your arguments were not within valid ranges");
            }
            catch (Exception exc)
            {
                Console.WriteLine("Crap!");
                Console.WriteLine(exc.Message);
            }

If an exception originates within the the scope of the try block and if the exception is not caught at a lower level, it will bubble up to the code containing this try-catch statement.  The type of the exception object will then be compared to the exception types specified in the catch blocks, starting with the first block.  If a matching type is found, the code in that catch block will execute and the exception will not propagate further up the call stack.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: