#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