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

text
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;
}
  1. text ← 12

    5int main() {6    std::string text→ 12 = "12"; //@text="abc", "7"
  2. 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=12
  3. std::cout << "input=" << text << std::endl;

    15    std::cout << "input=" << text12 << std::endl;16    return 0;17}
    outputinput=12
  1. text ← abc

    5int main() {6    std::string text→ abc = "abc";
  2. try

    8try {9    int value = std::stoi(textabc);10    std::cout << "value=" << value << std::endl;
  3. 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=invalid
  4. std::cout << "input=" << text << std::endl;

    15    std::cout << "input=" << textabc << std::endl;16    return 0;17}
    outputinput=abc
  1. text ← 7

    5int main() {6    std::string text→ 7 = "7";
  2. 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=7
  3. std::cout << "input=" << text << std::endl;

    15    std::cout << "input=" << text7 << std::endl;16    return 0;17}
    outputinput=7