TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  ERR#008

This rule is Obsolete
Synopsis:Do not throw exceptions as a way of reporting uncommon values from a function
Language:C++
Severity Level:9
Category:Error Handling


Description:

A consequence of the rule that exceptions should only be thrown if a function fails to do what it is expected to, is that exceptions should not be used as a way of reporting uncommon values from a function (see [ERR#007]).

It is important to remember why exceptions are a bad choice in these situations. If an exception is thrown, that exception must be handled, or the control flow of the program will change in a way that cannot be predicted. Throwing an exception for the sole purpose of changing the control flow is therefore not recommended.

Your code can be difficult to understand if you throw exceptions in many different situations, ranging from a way to just report unusual threads in your code to reporting fatal run-time problems. Exception handling is also often a very inefficient way to change the control flow in a program, compared to passing along error codes.

The find() function in the standard library is a good example of a function that could fail, but for which throwing an exception is inappropriate. The standard library uses iterators to traverse through collections of objects. The iterators are modeled after pointers, and ordinary pointers are therefore a special case of iterators. An input iterator is a special kind of iterator that allows you to read one element at the time in a forward direction only. If such an object is assigned to an element in a collection, it will eventually, after being incremented a number of times, be equal to the iterator pointing at the last element in the collection.

template<class InputIterator, class T>
InputIterator
find(InputIterator first, InputIterator last, 
     const T& value);

The function find() is defined to return the first iterator between first and last element (but not counting last itself) that points to a T equal to value . If no such value is found, it will return the last iterator. It is quite common not to find what you are looking for, so it is not reasonable to call it a programming failure if that happens. Therefore find() is defined to return last if value was not found in the sequence.



Literature References:
ISC++ Rec 12.4