Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do library implementers decide when to throw an exception vs. exhibit undefined behavior?

Tags:

c++

exception

Specifically considering the C++ string class constructor spec, we have:

string (const string& str, size_t pos, size_t len = npos);
string (const char* s, size_t n);

which are essentially of the same form/intent, excepting string vs. c-string. The exception specification however is very different:

If pos is greater then str's length, an out_of_range exception is thrown.

If n is greater than the array pointed by s, it causes undefined behavior.

I wonder why this is? Performance aside, when is it a good idea to throw an exception vs. permitting "undefined behavior"? The answer would seemingly depend on the following:

  • the client's ability to recognize the fault a priori (i.e. the client is much less likely to recognize a potential issue with file access than with, say, popping from an empty stack that the client has explicitly been using)
  • the client's interest in handling the potential issue (i.e. perhaps file access issues more often need to be handled, because less predictable?)
  • what "makes the most sense" from the implementer's standpoint (perhaps the string version throws because it is more connected to c++ style, hence exception semantics)
like image 883
jwalk Avatar asked Oct 20 '25 08:10

jwalk


1 Answers

The difference in the two cases is simply that in the first one, it is possible for the implementation to check if there is an error in the parameter passed, while in the second one it is impossible (there is no way of checking which is the length of the string, since only a pointer is passed).

So the general rule could be the following:

  1. If possibile, check a possible failure condition and raise an exception;
  2. otherwise, nothing can be done from the implementer point of view, and in the specification of the function document the possibility of an undefined behaviour.
like image 174
Renzo Avatar answered Oct 22 '25 23:10

Renzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!