How to use thrown exceptions by functions?

There are a ton of functions I see that says "Throw an exception if fail", or something along that line.

IE. If no conversion could be performed, an invalid_argument exception is thrown.--Stoi

I'm wondering how to use this invalid_argument. I've tried reading the page on invalid_argument and exceptions, but to be honest, I feel more lost after reading them.

So for example, if I were to use stoi and take in a user input string, and convert it to int. If it cannot be converted, how do I tell the computer to detect it and ask the user to input again?

1
2
3
4
5
6
7
8
9
10
11
12
  IE

#include <iostream>
using namespace std;

void main(){
string userinput;

int userinputINT = stoi(userinput);
//code here to detect if stoi fails
}


The normal way is to use a try-catch method. Here is just a quick (not great example, but whatever) example of how you could use it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <stdexcept>

int main() {
    std::string userinput, userinput2;
    int result, result2;
    while (true) {
        try {
            std::cin >> userinput >> userinput2;
            result = std::stoi(userinput);
            result2 = std::stoi(userinput2);
            break; // get out of the while loop
        } catch (const std::invalid_argument& ia) {
            std::cerr << "Invalid Argument: " << ia.what() << "\n";
            std::cerr << "Please try again: "
            // it should now loop around until no exception is thrown:
        }
    }

    //...

    return 0;
}
Last edited on
Thanks for the help!

I'm wondering, what is invalid_argument? A bool?

Is there any ways of using an if statement to it?
what is invalid_argument? A bool?

http://lmgtfy.com/?q=C%2B%2B+invalid_argument
Last edited on
Topic archived. No new replies allowed.