I may be misunderstanding how std::cin.exceptions
is supposed to work. Here is a simple example:
#include <iostream>
int main(){
std::cin.exceptions(std::ios_base::failbit);
int i=0;
try{ std::cin >> i; }
catch(std::ios_base::failure &b){ std::cout << "exception caught\n"; }
}
compiling with g++ --std=c++11
, then running with an invalid input, such as a non-numeric character like 'f', does not throw any exception, e.g. I don't see "exception caught". This is confusing to me because I'm assuming that when attempting to read an int, cin
will set the stream state to failbit
, and the first line in my code says to throw an exception whenever this happens. In that case, why do I not see an exception?
here is the output when I type g++ -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
update: it seems to be a problem specific to the compiler described above, (or at least my particular copy of it). As noted by one of the comments, replacing by
std::cin.exceptions(std::ios_base::badbit);
doesn't fix the issue, but strangely,
std::cin.exceptions(std::ios_base::failbit | std::ios_base::badbit);
does.