#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 software development and sailing.

3 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!

  3. Nyerguds says:

    Okay… but how can you view the exception info from compiled libraries? Intellisense doesn’t seem to do that.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: