Is it possible to exclude exceptions defined in the C ++ standard library?

I was wondering if this should be considered OK to throw exceptions that are defined in the C ++ standard library, instead of creating my own class. For example, consider the following (dumb) function that takes a single line as an 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 then, of course, we could do something 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 that the std::stoi family of functions throws a std::invalid_exception when they receive an invalid argument; that when the idea came up above.

+5
source share
1 answer

Yes, it’s great to use standard exception classes for your own purposes. If they are appropriate for your situation, go ahead (but feel free to define your own class if / if the standard class is not suitable).

Also note that you can get standard classes, so if you can add significantly more precision or new behavior that are not in the standard class, you can still use it as a base class.

A better question (IMO) would be when it would be wise to define your own exception classes (which, at least, do not follow from the standard ones). One obvious candidate here would be if you want to support something like what() that returns a UTF-16 or UTF-32 encoded string, so the “margin” “std :: exception” would not provide much (if any are), and you're pretty much stuck from the beginning from the very beginning.

+4
source

All Articles