#855 – Throwing an Exception

Your code can throw an exception to indicate that some sort of error occurred.  You’ll typically do this to indicate that something has gone wrong and the execution of the method cannot continue.

To throw an exception, you create an instance of the System.Exception class, or one of its derived classes, to contain information about what went wrong.  You use the throw statement to throw the exception.  Control returns immediately to the calling function and the exception “bubbles up” the call stack, looking for a calling method that can handle the exception.

Below, an exception is thrown if numTimesToBark is too large.

        public void Bark(int numTimesToBark)
        {
            if (numTimesToBark > 10)
            {
                string message =
                    string.Format("Dogs can bark at most 10 times.  {0} is too much barking",
                                  numTimesToBark);
                Exception exc = new Exception(message);
                throw exc;
            }

            for (int i = 0; i < numTimesToBark; i++)
                Console.WriteLine("Woof");
        }
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.

2 Responses to #855 – Throwing an Exception

  1. Pingback: Dew Drop – May 30, 2013 (#1,557) | Alvin Ashcraft's Morning Dew

  2. Pingback: #881 – When to Throw Exceptions | 2,000 Things You Should Know About C#

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: