Exceptions
Standard Exceptions
The standard library throws typed exceptions for common errors such as invalid numeric input.
standard exception
Catch a standard exception by its type, then print your own stable message for the user.
Standard Exceptions
standard_exceptions.cpp
Replay: real traced execution (multi-file project)
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string text = "12";
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 = "abc";
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 = "7";
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;
}
text ← 12
5int main() {6 std::string text→ 12 = "12"; //@text="abc", "7"value ← 12
8try {9 int value→ 12 = std::stoi(text12);10 std::cout << "value=" << value12 << std::endl;11} catch (const std::invalid_argument& error) {outputvalue=12std::cout << "input=" << text << std::endl;
15 std::cout << "input=" << text12 << std::endl;16 return 0;17}outputinput=12
text ← abc
5int main() {6 std::string text→ abc = "abc";try
8try {9 int value = std::stoi(textabc);10 std::cout << "value=" << value << std::endl;catch (const std::invalid_argument& error)
10 std::cout << "value=" << value << std::endl;11} catch (const std::invalid_argument& error) {12 std::cout << "parse=invalid" << std::endl;13}outputparse=invalidstd::cout << "input=" << text << std::endl;
15 std::cout << "input=" << textabc << std::endl;16 return 0;17}outputinput=abc
text ← 7
5int main() {6 std::string text→ 7 = "7";value ← 7
8try {9 int value→ 7 = std::stoi(text7);10 std::cout << "value=" << value7 << std::endl;11} catch (const std::invalid_argument& error) {outputvalue=7std::cout << "input=" << text << std::endl;
15 std::cout << "input=" << text7 << std::endl;16 return 0;17}outputinput=7