guY
guY

Reputation: 65

Can't catch exception std::stoi

Whenever I input anything other than an integer, I was hoping for the catch block to execute but instead I get this error:

Unhandled exception at 0x002D0C39 in A03.exe: Stack cookie instrumentation code detected a stack-based buffer overrun. occurred

which takes me to:

Exception thrown at 0x76D44192 in A03.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0116D83C.

Unhandled exception at 0x000608B9 in A03.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.

I've tried varieties of catch blocks and exceptions with the same error. Can someone tell me what I'm doing wrong? Thank you!

Here is the code:

int main() {
    while (true) {
        std::string input;
        int num = 0;

        std::cout << "What number do you want to show?";
        std::cin >> input;
        try 
        {
            num = std::stoi(input);
            if (num >= 0 && num < 10)
            {
                std::cout << "FILLER: This will draw the number";

                exit(0);
            }
            else {
                std::cout << "FILLER: This is the else";
                exit(1);
            }
        }
        catch (std::runtime_error e) 
        {
            std::cout << e.what();
            //std::cout << "That is not a valid number." << '\n';
        }
    }
    return 0;
}

UPDATE: Edited the exception handler, but still erroring:

int main() {
    while (true) {
        std::string input;
        int num = 0;

        std::cout << "What number do you want to show?";
        std::cin >> input;
        try 
        {
            num = std::stoi(input);
            if (num >= 0 && num < 10)
            {
                std::cout << "FILLER: This will draw the number";

                exit(0);
            }
            else {
                std::cout << "FILLER: This is the else";
                exit(1);
            }
        }
        catch (std::invalid_argument &e) 
        {
            std::cout << e.what();
            //std::cout << "That is not a valid number." << '\n';
        }
    }
    return 0;
}

Upvotes: 0

Views: 3210

Answers (1)

Coral Kashri
Coral Kashri

Reputation: 3506

The exception that this function throws is std::invalid_argument, which have the following inheritance connections: std::exception <- std::logic_error <-std::invalid_argument. This means you can use any of the above as the catch type (and also ...), to catch the exception. std::runtime_error is not one of the options (std::exception <- std::runtime_error).

Change your catch section to:

catch (std::invalid_argument &e) {
    std::cout << e.what();
    //std::cout << "That is not a valid number." << '\n';
}

Read About:

std::invalid_argument
std::runtime_error
std::exception - Exceptions tree

Upvotes: 2

Related Questions