Error Handling with Exceptions: How to Throw

By | November 8, 2010

This article is part of a longer running series on Error Handling with Exceptions.

Fortunately, throwing exceptions is very easy in most languages, and the best recommendation is to throw in such a way that all information required by the exception is populated. When creating custom exception types, care should be taken to ensure that the user of the exception (when throwing) is not placed under undue hardship while populating its required information. The following recommendations help to eliminate such a burden:

  • Create a macro if the language doesn’t populate location information regarding where an exception was thrown. This macro should internally calculate the location and add that information to the exception.
  • Ensure that exceptions can be created and thrown in a single statement; any difficulty associated with throwing an exception will decrease the likelihood that the exception is used in practice. Consider these code samples:
MyExceptionType ex;
throw ex;


throw MyExceptionType().SetArg1("Foo").SetArg2("Bar");

The first sample requires that the user create the exception type and set each value within its own statement. The second example doesn’t prevent that usage pattern, but does facilitate the more concise version.

Leave Your Comment

Your email will not be published or shared. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Please wrap all source codes with [code][/code] tags. Powered by