Exceptions
Standard Exceptions
The standard library throws typed exceptions for common errors such as invalid numeric input.
Standard Exceptions
standard_exceptions.cpp
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string text = ;
try {
int value = std::stoi(text);
std::cout << "value=" << value << std::endl;
} catch (const std::invalid_argument& error) {
std::cout << "parse=invalid" << std::endl;
}
std::cout << "input=" << text << std::endl;
return 0;
}
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string text = ;
try {
int value = std::stoi(text);
std::cout << "value=" << value << std::endl;
} catch (const std::invalid_argument& error) {
std::cout << "parse=invalid" << std::endl;
}
std::cout << "input=" << text << std::endl;
return 0;
}
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string text = ;
try {
int value = std::stoi(text);
std::cout << "value=" << value << std::endl;
} catch (const std::invalid_argument& error) {
std::cout << "parse=invalid" << std::endl;
}
std::cout << "input=" << text << std::endl;
return 0;
}
standard exception
Catch a standard exception by its type, then print your own stable message for the user.