Is it OK to throw exceptions defined in the C++ standard library? -


i wondering whether or not considered ok throw exceptions defined in c++ standard library, instead of creating own class. example, let's consider following (stupid) function takes 1 string argument:

#include <stdexcept>  #include <iostream> #include <string>  bool useless_function(const std::string& str) {     if (str == "true")         return true;      else if (str == "false")         return false;      else         throw std::invalid_argument("expected argument of either true or false"); } 

and of course, like:

int main(int argc, const char** argv) {     try {         const bool check = useless_function("not true");     }      catch (std::invalid_argument& error) {         std::cerr << error.what() << '\n';     }      return 0; } 

i read here std::stoi family of functions throw std::invalid_exception exception when receive invalid argument; that's above idea came from.

yes, it's fine use standard exception classes own purposes. if fit situation well, go ahead (but don't hesitate define own class when/if no standard class fits well).

also note can derive standard classes, if can add greater precision or new behavior isn't present in standard class, may still want use base class.

the better question (imo) when make sense define own exception classes (that don't @ least derive standard ones). 1 obvious candidate here if want support what() returns string in utf-16 or utf-32 encoding, "stock" "std::exception" wouldn't provide (if any) utility, , you're pretty stuck starting on beginning.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -