Created
November 9, 2022 02:38
-
-
Save mshafae/e319fd4912f979828fc7aca6a714820d to your computer and use it in GitHub Desktop.
CPSC 120 Example handling of exceptions generated by std::stoi()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Gist https://gist.github.com/e319fd4912f979828fc7aca6a714820d | |
#include <iostream> | |
#include <string> | |
int main(int argc, char const* argv[]) { | |
std::string a_big_number{"65536"}; | |
int the_integer_value{-1}; | |
try { | |
the_integer_value = std::stoi(a_big_number); | |
} catch (std::exception const& e) { | |
std::cout | |
<< "Exception! Looks like \"" << a_big_number | |
<< "\" isn't an integer because stoi() couldn't make sense of it.\n"; | |
} | |
std::cout << "The integer value of \"" << a_big_number << "\" is " | |
<< the_integer_value << "\n"; | |
std::string this_is_not_a_number{ | |
"sixty five thousand five hundred and thirty six"}; | |
int value_never_changes{-1}; | |
try { | |
value_never_changes = std::stoi(this_is_not_a_number); | |
} catch (std::exception const& e) { | |
std::cout | |
<< "Exception! Looks like \"" << this_is_not_a_number | |
<< "\" isn't an integer because stoi() couldn't make sense of it.\n"; | |
} | |
std::cout << "The integer value of \"" << this_is_not_a_number << "\" is " | |
<< value_never_changes << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment