I am trying to write a function that prompts a user for a five digit number, and I want to write an exception block to handle bad input incase the user tries to enter a string or some non-integer input.
I know how to write an exception handling block for something like a division function where you thrown an exception for the denominator being 0, but I have no clue how to do this for input that I have no control over.
The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.
Example: Exception handling using try... In the example, we are trying to divide a number by 0 . Here, this code generates an exception. To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.
First of all, I'd generally advise against this -- bad input from the user is nearly the rule rather than the exception.
If you insist on doing it anyway, you'd probably do it by accepting anything as input, and then throwing an exception when/if it's not what you want:
// Warning: untested code.
// Accepting negative numbers left as an exercise for the reader.
int get_int(std::istream &is) {
std::string temp;
std::getline(temp, is);
for (int i=0; i<temp.size(); i++)
if (!isdigit(temp[i]))
throw std::domain_error("Bad input");
return atoi(temp);
}
I repeat, however, that I don't think this is generally a good idea. I'd note (for one example) that iostreams already define a fail
bit specifically for situations like this (and the normal operator>>
to read an int uses that mechanism).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With