Exceptions: throw, try, catch
intermediate25 min readLesson 117 of 204
The standard exception family, catch-by-const-ref, handler ordering, and when exceptions beat return codes.
C++ error handling has two channels: return values for expected outcomes, and exceptions for conditions the caller cannot quietly ignore.
#include <stdexcept>
int parse_port(const std::string& s) {
int value = std::stoi(s); // throws std::invalid_argument
if (value < 0 || value > 65535)
throw std::out_of_range("port out of range: " + s);
return value;
}
The throwing family you will actually use, all in <stdexcept>:
std::invalid_argumentโ the input is not parseablestd::out_of_rangeโ parseable but outside the legal domainstd::runtime_errorโ failures only visible at runtime (I/O, network)std::logic_errorโ the program broke its own contract
Throw by value, catch by const&:
try {
int port = parse_port(user_input);
use(port);
} catch (const std::out_of_range& e) {
std::cerr << "bad port: " << e.what() << "\n";
} catch (const std::exception& e) {
std::cerr << "error: " << e.what() << "\n"; // base-class fallback
}
Catch order matters: handlers are tried top-down, so put derived types
before bases. A bare catch (...) swallows everything โ reserve it for
thread boundaries and last-resort barriers.