Thursday, May 29, 2014

When and how to use exceptions in C++

These are really just some thoughts I wrote down, about how to avoid the mess that can result from handling errors using exceptions. I'm hoping to get feedback, based on the experience of others.

I started thinking about this after reading this blog post by the creator of ZeroMQ.

A function or method should throw an exception under three circumstances:
  1. If there's something wrong with an input argument.
  2. If a required condition isn't met for running the function.
  3. An operating system error occurs, such as a failure to allocate memory, or to access a device or file. This is really a special case of #2.
Therefore, the documentation should clearly specify requirements for input arguments, and the conditions that must exist for the function to execute correctly. It should also state what exceptions will be thrown if those specifications aren't met.

Any other exceptions are the result of bugs in the function's implementation, and shouldn't be included in the documentation. For example, the function may call another function that throws an invalid_argument error. However, if the calling function has total control over the argument being passed, then that exception should never be raised.

Circumstance #3 could be re-phrased as a "system event", rather than a system error. For example, an exception could be thrown when a signal is received and handled by the process.

No comments:

Post a Comment