Runtime errors and undefined behavior
C++ runtime error: terminate called after throwing an instance of
This runtime message means an exception escaped the program without a matching handler, so the runtime called std::terminate. Read the exception type and the following what() line to find the operation that failed.
Read both lines of the message
A typical diagnostic names the exception type, then prints what(): followed by a short description. std::invalid_argument with what(): stoi means stoi could not parse an initial number. std::out_of_range with what(): basic_string::substr means the requested starting position exceeded the string’s size. The what() text comes from the standard library, so identify the operation from the exception type and the text together.
Failing C++17 example
#include <iostream>
#include <string>
int main() {
std::string text = "abc";
int value = std::stoi(text);
std::cout << value << '\n';
return 0;
}
Runtime diagnostic core:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoiThe runtime?s what() text depends on the standard library. MSVC may also exit with a nonzero status.
Fixed example
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string text = "abc";
try {
int value = std::stoi(text);
std::cout << value << '\n';
} catch (const std::invalid_argument&) {
std::cout << "Enter a whole number\n";
}
return 0;
}
Expected output:
Enter a whole number
Stop where the exception is thrown
A debugger can stop at the throw site before the program terminates. In GDB, run catch throw, then run and bt to inspect the backtrace. In Visual Studio, open Exception Settings and enable breaking when C++ exceptions are thrown.
Recognize common exception messages
These what() strings are common in libstdc++; other standard libraries can use different text.
what() text | Likely source |
|---|---|
stoi | std::stoi could not parse a number or the result did not fit in an int; see the conversion section above. |
stol | std::stol could not parse a number or the result did not fit in a long. |
basic_string::substr | substr received a starting position greater than the string size; see the string-position section above. |
vector::_M_range_check | std::vector::at received an invalid index; see the vector range-error guide. |
map::at | std::map::at did not find the requested key; the example below demonstrates it. |
Failing C++17 example
#include <iostream>
#include <map>
#include <string>
int main() {
const std::map<std::string, int> scores{{"Ada", 7}};
std::cout << scores.at("Grace") << '\n';
return 0;
}
Runtime diagnostic core:
what(): map::atMSVC reports a nonzero exit for the uncaught exception. The message text depends on the standard library.
Report an uncaught exception
As a last resort, catch std::exception at the top of main, print e.what(), and return a failure status. This gives the user a useful message when no local recovery makes sense.
Top-level handler example
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
int main() {
try {
const std::map<std::string, int> scores{{"Ada", 7}};
std::cout << scores.at("Grace") << '\n';
} catch (const std::exception& e) {
std::cerr << "Uncaught: " << e.what() << '\n';
return 1;
}
return 0;
}
The program prints nothing to standard output. With GCC’s standard library, it writes this line to standard error and exits with status 1. Other libraries word the what() text differently.
Uncaught: map::atValidate conversion input
std::stoi converts an initial numeric portion of a string. It throws std::invalid_argument when no conversion is possible and std::out_of_range when the value cannot fit in int. Catch these exceptions at a boundary where the program can report invalid input or ask again. If the whole string must contain a number, also check the optional position output; stoi can accept a numeric prefix followed by other characters.
Check string positions
std::string::substr throws std::out_of_range when its starting position is greater than size(). A position equal to size() is valid and returns an empty string. Check the position before calling when it comes from user input or arithmetic. Do not confuse a length that extends beyond the end with an invalid start; substr limits the returned length to available characters.
Handle only the errors you can recover from
Put the operation that can throw inside a try block, then catch the specific exception types you expect. Print a useful message or return an error status. A catch-all can prevent an abrupt termination but may hide programming defects. Catch by const reference and keep the handler near a meaningful recovery boundary. If no recovery is possible, let the exception reach a deliberate top-level handler.
Keep vector access on its own guide
A vector::at() failure can also produce std::out_of_range with vector::_M_range_check in libstdc++. See the vector guide for the vector-specific range-check message. Always use the operation and exception text together; the type alone may not identify which input or index was invalid.
Exercise
Handle substr when its requested starting position is beyond the string. Report a useful message instead of letting the exception terminate the program.
Broken program
#include <iostream>
#include <string>
int main() {
std::string text = "cat";
std::cout << text.substr(5) << '\n';
return 0;
}
Runtime diagnostic core:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substrSample input: none.
Expected output after the fix:
Position outside text
Hint 1: Check why substr throws for this starting position. Hint 2: Catch std::out_of_range around the call.
Show one possible solution
#include <iostream>
#include <stdexcept>
#include <string>
int main() {
std::string text = "cat";
try {
std::cout << text.substr(5) << '\n';
} catch (const std::out_of_range&) {
std::cout << "Position outside text\n";
}
return 0;
}
Expected output:
Position outside text
Related guides
- Check vector indices before access
- Validate input before converting it
- Handle input left before std::getline
Keep learning with CppPath
Continue with the Exceptions lesson. The full lesson includes a quiz and a checked coding challenge with a free account.