C++ stoi() function and exception handling

Asked 2 years ago, Updated 2 years ago, 26 views

std::string str = "129380129831213981";
int conv = std::stoi(str);

Running this code causes an Out of range exception because the number you are trying to convert exceeds the range of int.

So I wrote a try-catch sentence as below

try {
    std::string str = "129380129831213981";
    int conv = std::stoi(str);
} } catch (const std::string& expn) {
    std::cout << expn << ": Out of integer's range\n";
}

This does not process exceptions and forces them to terminate.

According to the principle of 'Stack unwinding', the exception data that occurred while calling the stoi() function in the try statement is returned to the try statement, and is not this data thrown into the catch statement and processed?

Please answer me if I misunderstand something.

c++

2022-09-22 19:10

1 Answers

You asked yourself, but I'll make up for it.

std::stoi() is a function that converts std:string to int. Therefore, if a string that exceeds the expression range of int is entered, the std::out_of_range exception occurs.

Total int can be expressed from a minimum -2147483648 to a maximum 2147483647. The "129380129831213981" you used for conversion goes beyond the expression range of int, so you must use std:stoll().

The reason why the exception was not received successfully in try~catch is that it was written to receive std::string instead of the type of exception thrown in the catch syntax. Sometimes you make this mistake because you don't know what a throwaway exception is, but you can get most of the exceptions by using std::exception or ....

All exceptions from the C++ standard library inherit std::exception. ... means all exceptions. Therefore, you will get most exceptions if you create as below.

try {
    std::string str = "129380129831213981";
    int conv = std::stoi(str);
} } catch (const std::exception& expn) {
    std::cout << expn.what() << ": Out of integer's range\n";
} } catch (...) {
    std::cout << ": Unknown error\n";
}

Note that Stack unwinding means how the stack is cleared until catch is reached when an exception is thrown. It's not because of Stack unwinding that comes back to the try point, it's the grammatical function of try~catch.


2022-09-22 19:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.