The exceptions in C++ propagate and they get handled by unwinding the stack. A throw abandons the current function, it runs the destructors of everything that it passes on the way out, and it looks for a matching catch further up. The handler that matches is the first one in the nearest enclosing try block, and everything below it is cleaned up automatically on the way.
This is the first lesson in the Exceptions and Robust Code module, and the next lesson in this module is about "What Is Exception Safety and When Is noexcept Right?".
Throwing and catching
A try block contains the code that might fail, and one or more catch handlers deal with the failures.
#include <iostream>
#include <stdexcept>
#include <string>
int charge_card(int amount) {
if (amount <= 0) {
throw std::invalid_argument("amount must be positive");
}
if (amount > 1000) {
throw std::runtime_error("amount exceeds the card limit");
}
return amount;
}
int main() {
try {
std::cout << "charging " << charge_card(250) << '\n';
std::cout << "charging " << charge_card(5000) << '\n';
std::cout << "this line never runs\n";
} catch (const std::invalid_argument& error) {
std::cout << "invalid: " << error.what() << '\n';
} catch (const std::exception& error) {
std::cout << "failed: " << error.what() << '\n';
}
std::cout << "checkout continues\n";
return 0;
}The output shows the exception being caught and the program continuing.
charging 250
charging failed: amount exceeds the card limit
checkout continuesAnd the handler for the std::invalid_argument comes first, so it is checked first. The order matters. The more specific handler has to be listed before the more general one, or the general one will swallow everything.
The standard exception hierarchy
The standard library provides a family of the exception types, and all of them are derived from the std::exception.
the type what it means
-------------------------- ----------------------------------------------
std::exception the base, with a what() method
std::runtime_error an error that could not be detected
at compile time
std::logic_error a violation of the program's own logic
std::invalid_argument a specific logic error
std::out_of_range a specific logic error
std::domain_error a specific logic error
std::overflow_error a specific runtime error
std::underflow_error a specific runtime error
std::range_error a specific runtime error
And catching the std::exception by a reference catches everything that the standard library throws. Catching the ellipsis catches everything, including the exceptions that do not derive from it, and you lose the ability to read a message.
#include <exception>
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::out_of_range("index 5 is past the end");
} catch (const std::exception& error) {
std::cout << "exception: " << error.what() << '\n';
}
try {
throw 42;
} catch (const std::exception& error) {
std::cout << "never printed\n";
} catch (int code) {
std::cout << "caught a plain int: " << code << '\n';
}
return 0;
}The output shows both of the handlers working, and the second one catching a value that is not an exception object at all.
exception: index 5 is past the end
caught a plain int: 42Propagation through the stack
An exception with no handler in the current function propagates to the caller. It keeps going until something catches it, or until it reaches the main and it calls the std::terminate.
#include <iostream>
#include <stdexcept>
void log_payment() {
std::cout << "logging the payment\n";
}
void process_payment(int amount) {
std::cout << "processing " << amount << '\n';
log_payment();
if (amount <= 0) {
throw std::invalid_argument("amount must be positive");
}
std::cout << "payment accepted\n";
}
int main() {
try {
process_payment(-1);
} catch (const std::exception& error) {
std::cout << "caught: " << error.what() << '\n';
}
return 0;
}The output shows the calls that happened before the throw and the handler that eventually caught it.
processing -1
logging the payment
caught: amount must be positiveAnd notice that "payment accepted" never printed, and the stack was unwound through the log_payment and the process_payment on the way out.
Defining your own exception type
Deriving from the std::exception gives you a type that the caller can catch specifically, and the what() lets you carry a message.
#include <exception>
#include <iostream>
#include <string>
class PaymentError : public std::exception {
public:
explicit PaymentError(const std::string& message) : message_(message) {}
const char* what() const noexcept override {
return message_.c_str();
}
int code() const noexcept {
return code_;
}
void set_code(int code) noexcept {
code_ = code;
}
private:
std::string message_;
int code_ = 0;
};
int main() {
try {
throw PaymentError("the payment gateway timed out");
} catch (const PaymentError& error) {
std::cout << "payment error: " << error.what() << '\n';
}
return 0;
}The output shows the custom type being caught specifically.
payment error: the payment gateway timed outRethrowing and the exception_ptr
Inside a catch block you can rethrow the current exception, and you can capture it for later with the std::exception_ptr.
#include <exception>
#include <iostream>
#include <stdexcept>
int main() {
std::exception_ptr saved;
try {
throw std::runtime_error("temporary failure");
} catch (...) {
saved = std::current_exception();
std::cout << "saved for later\n";
}
try {
std::rethrow_exception(saved);
} catch (const std::exception& error) {
std::cout << "rethrown: " << error.what() << '\n';
}
return 0;
}The output shows the exception being saved and rethrown.
saved for later
rethrown: temporary failureAnd there is a convention that is worth learning. You throw by value and you catch by a const reference. Throwing a pointer or catching by value means a copy, and catching by value on a polymorphic type slices the exception.
The cost of exceptions
Throwing is not cheap. It allocates, it unwinds the stack, and it runs every destructor on the way out. A hot loop that throws once per thousand iterations will spend most of its time in the exception machinery.
And the practical rule is this. You use the exceptions for the exceptional case, such as a failed connection, a malformed input or a missing file. And you return a value or a bool for the ordinary case that happens often.
Quick reference
- A throw unwinds the stack to the nearest matching catch, and it runs the destructors on the way.
- You list the most specific handler first, and the first match wins.
- You catch by a const reference to avoid the copying and to avoid the slicing.
- You derive the custom exceptions from the
std::exceptionand you override thewhat(). - You catch the ellipsis as a last resort, because you lose the message.
- You use the exceptions for the rare failures and not for the ordinary control flow.
Try it yourself: write a function that validates a payment amount, and that throws the std::invalid_argument for a non-positive value and the std::out_of_range for one above a limit. Catch each of them specifically in one function and with a single std::exception handler in another, and compare the messages that you can print. Then add a custom exception type that carries an error code as well as a message.