Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do std::stof, std::stod, and std::stold handle errors with exceptions?

What is the rationale for why std::stof, std::stod, and std::stold throw exceptions?

http://en.cppreference.com/w/cpp/string/basic_string/stof

Input errors are a commonly used example for when error handling via exceptions is a poor fit (usually phrased with the quirky circular reasoning of "exceptional circumstances" but still a good example). It's not as if other error handling mechanisms are somehow verboten in the C++ standard library. For example, another C++11 newcomer, the std::unordered_map::insert family, indicates failure using the second element in a std::pair<iterator,bool> return type. Failure inside a std::unordered_map::insert function seems much more "exceptional" than an input error. Without attempting to insert, it's possible to guarantee that an insert will succeed but without parsing it's not possible to guarantee that parsing will succeed.

I'm just wondering what the rationale was at the time these functions were accepted into the standard. Hopefully it's published somewhere or a committee member can drop by and shed some light on this. I'm not asking for a comprehensive treatise on the advantages and disadvantages of exceptions vs other mechanisms.

like image 574
Praxeolitic Avatar asked Jan 11 '16 01:01

Praxeolitic


1 Answers

The original paper, N1803: Simple Numeric Access uses exceptions. The paper however doesn't explain anything about where any part of their design design comes from (like why they completely ignore allocators!). The later revisions to it (N1982, N2408) also say nothing about why they throw exceptions. If there is another record of this beyond those papers, I am not aware of it.

However, I can hazard a guess. We can see that the very first draft of the paper throws exceptions. And it does not appear that this was ever in dispute. This likely stems from the view that exceptions are the standard method for indicating the failure of an operation in C++, and in particular the C++ standard library.

Some standard library types have other error mechanisms (iostreams). But generally speaking, exceptions are the default case.

like image 124
Nicol Bolas Avatar answered Oct 21 '22 02:10

Nicol Bolas