#859 – The Scope of a try Block

A try/catch block consists of:

  • try statement followed by a block of code contained in braces { }
  • One or more catch statements, optionally indicating the type of exception that can be caught

The idea of the try block is to indicate a block of code for which an exception can be caught.  An exception that occurs as a result of calling any of the statements in the try block can be caught in the associated catch block.

In the example below, we catch exceptions that occur in the Dog constructor, the Dog.Bark call, or the Dog.Print call.  An exception thrown from any of these methods, or code that they call, will be caught in the catch block.

                try
                {
                    // Construct a dog
                    Dog d = new Dog("Kirby", 15);

                    // Bark at volume=11
                    d.Bark("Woof", 11);

                    // Print info
                    d.Print();
                }
                catch (Exception exc)
                {
                    Console.WriteLine("Something went wrong.  Message:");
                    Console.WriteLine(exc.Message);
                }

859-001

Advertisement

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

One Response to #859 – The Scope of a try Block

  1. Pingback: Dew Drop – June 5, 2013 (#1,561) | Alvin Ashcraft's Morning Dew

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: