#913 – How to Document that a Method Can Throw an Exception

You can use XML Documentation to document the fact that a method can throw an exception.  You use the Exception tag to indicate the type of exception that can be thrown.  You can also provide a comment related to the exception, which will show up in an XML Documentation file that you generate.

        /// <summary>
        /// Print somebody's name
        /// </summary>
        /// <param name="name">Name to be printed</param>
        /// <exception cref="ApplicationException">Will throw exception if name is Mortimer</exception>
        /// <exception cref="JustBecauseException">I throw this exception on Tuesdays</exception>
        static void PrintMyName(string name)
        {
            if (name.ToLower().Equals("mortimer"))
                throw new ApplicationException("I don't like the name Mortimer");

            if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
                throw new JustBecauseException("Tuesday is my day off");

            Console.WriteLine(string.Format("Your name is {0}", name));
        }

Intellisense will now include a list of the exceptions that might be thrown, when displaying the method’s name.
913-001

 

If you generate a XML Documentation file, it will also include this information.

913-002

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 #913 – How to Document that a Method Can Throw an Exception

  1. Rico says:

    For better IDE support for documenting thrown exceptions, check out Exceptional for ReSharper (http://exceptional.codeplex.com/)

  2. “I don’t like the name Mortimer” — made my morning! Thanks!

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: