I am a (somewhat) experienced python programmer trying to migrate to C++. I want to be able to catch invalid user input. For instance, if a variable requires an integer, and
By default, C++ streams don't throw upon ill-formed input: it isn't exceptional that input is wrong. It is normal. The C++ approach to indicate input failure is to put the stream into failure state, i.e., to set the state flag std::ios_base::failbit. The easiest way to test for wrong input is to use something like
if (in >> value) {
process(value);
}
else {
deal_with_input_error(in);
}
Dealing with the input error typically amounts to clearing the stream's state (as long as it is failure mode it won't deal with the actual stream at all) and then to ignore() one or more of the offending characters.
If you really want to get an exception you can set an exception mask:
in.exceptions(std::ios_base::failbit);
try {
in >> value;
}
catch (std::ios_base::failure const& ex) {
// deal with the error
}
Whenever in.exceptions() & in.rdstate() is non-zero at the end of any of the members dealing with the state bits or the exception mask is called an exception thrown (i.e. calling in.exception(std::ios_base::failbit) may itself throw an exception). The exception thrown is of type std::ios_base::failure.
I recommend not to use the exception facilities in IOStreams! Input errors are normal and exceptions are for, well, exceptional errors. Using the conversion to bool after having read a value works rather well.