Things go wrong: a file is missing, the user types letters instead of a number, someone withdraws more money than they have. C++ lets a function throw an exception to say “something went wrong”, and other code can catch it and deal with it.
Tip: The browser editor on this site uses a small WebAssembly compiler that has exceptions switched off, so examples with
tryandthrowwon't run there. The outputs below come from g++ on a normal computer. Try them on your own machine!
try, throw and catch
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw runtime_error("cannot divide by zero");
}
return a / b;
}
int main() {
try {
cout << divide(10, 2) << "\n";
cout << divide(5, 0) << "\n"; // throws: the rest of try is skipped
cout << "This line never runs\n";
} catch (const exception& e) {
cout << "Error: " << e.what() << "\n";
}
cout << "The program keeps going\n";
return 0;
}Output (on your own computer with g++ – exceptions don't run in the browser editor)
5 Error: cannot divide by zero The program keeps going
throwstops the function right away and sends the exception up to whoever called it.try { ... }wraps code that might throw.catch (const exception& e)catches it.e.what()gives the message.
Think of it like this: Throwing an exception is like pulling the emergency cord on a train. Everything stops, and the person responsible (the
catch) comes to sort it out.
Standard exception types
<stdexcept> has ready-made types: runtime_error, invalid_argument, out_of_range and more. Some library functions throw them too, like stoi and vector::at:
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
int main() {
try {
int n = stoi("hello");
cout << n << "\n";
} catch (const invalid_argument& e) {
cout << "That is not a number\n";
}
vector<int> v = {1, 2, 3};
try {
cout << v.at(10) << "\n";
} catch (const out_of_range& e) {
cout << "Index 10 is out of range\n";
}
return 0;
}Output (on your own computer with g++ – exceptions don't run in the browser editor)
That is not a number Index 10 is out of range
Without exceptions
Many C++ programs (games, small devices, and this site's editor) don't use exceptions at all. Instead a function returns a value that says whether it worked. Both styles are common:
#include <iostream>
using namespace std;
bool safeDivide(int a, int b, int& result) {
if (b == 0) {
return false; // tell the caller it failed
}
result = a / b;
return true;
}
int main() {
int r;
if (safeDivide(20, 4, r)) {
cout << "Result: " << r << "\n";
}
if (!safeDivide(1, 0, r)) {
cout << "Division failed\n";
}
return 0;
}Output
Result: 5 Division failed
Remember: Use exceptions for things that are truly unusual. For checks you expect to fail often (like validating user input), a simple
ifis clearer.