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++
You asked yourself, but I'll make up for it.
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.
541 Unable to install versioned in Google Colab
697 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
547 Who developed the "avformat-59.dll" that comes with FFmpeg?
547 PHP ssh2_scp_send fails to send files as intended
529 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.