For example, -
short a;
cin>>a;
cout<<a;
Now, what if I insert a value bigger than 32,767? The program is going to crash. So I know how to handle exceptions, but something correct has to happen to throw an exception for the incoming wrong event. Like in a calculator, for a divide by zero exception, you will write-
try {if (divider = 0){then do stuff}}
. But in my above example, there is no correct event and directly the wrong even takes place. What I mean by that is, in my calculator example, the program can detect that the divider is 0 and a wrong event is about to happen, but in my example I can't do something like this- try{if(a>32767) {do stuff}}
, here my program can't detect the incoming wrong event as that wrong even takes place immediately, that is, the program can't detect that the value I have entered is more than it can take, because it anyways can't check my value as it bigger than its max value limit. So how can I prevent this kind of a exception?
CodePudding user response:
By default, iostreams don't throw exceptions at all. You can handle invalid inputs by checking the state of the input stream. Here is fixed version that won't crash:
short a;
if(std::cin >> a) {
std::cout << a;
} else {
std::cout << "won't fit, or not a number";
}
See Quentin's answer for how to enable iostream exceptions if you prefer to use them.
CodePudding user response:
Good thinking. @eeorika's anwser shows you how to query an I/O stream to know after the fact that parsing has failed.
You can also enable exceptions on a stream by using its exceptions
member function:
std::cin.exceptions(std::ios_base::badbit | std::ios_base::failbit);
short s;
// Will throw an exception of type `std::ios_base::failure` if the number does not fit
std::cin >> s;